Docs Menu

Docs HomeRealm

Read & Write Data - Flutter SDK

On this page

  • Read Operations
  • Find Object by Primary Key
  • Query All Objects
  • Query List of RealmObjects
  • Filter Results
  • Sort Results
  • Write Operations
  • Create Objects
  • Update Objects
  • Delete Objects
  • Background Writes

This page explains the Realm SDK methods that you can use to create, read, update, and delete data in a realm.

Example

About the Examples on This Page

The examples on this page use two Realm object types, Person and Team.

@RealmModel()
class _Person {
@PrimaryKey()
late ObjectId id;
late String name;
}
@RealmModel()
class _Team {
@PrimaryKey()
late ObjectId id;
late String name;
late List<_Person> crew;
}

Find an object by its primary key with Realm.find().

final luke = realm.find<Person>(lukePrimaryKey);

Retrieve a collection of all objects of a data model in the realm with the Realm.all() method.

final people = realm.all<Person>();

You can query any list of RealmObjects. For more information on querying, refer to Filter Results.

final config = Configuration.local([Person.schema, Team.schema]);
final realm = Realm(config);
final heroes = Team(ObjectId(), 'Millenium Falcon Crew', crew: [
Person(ObjectId(), 'Luke'),
Person(ObjectId(), 'Leia'),
Person(ObjectId(), 'Han'),
Person(ObjectId(), 'Chewbacca')
]);
realm.write(() => realm.add(heroes));
final lukeAndLeia = heroes.crew.query('name BEGINSWITH \$0', ['L']);

Filter a RealmList to retrieve a specific segment of objects with the Realm.query() method. In the query() method's argument, use Realm Query Language to perform filtering. Realm Query Language is a string-based query language that you can use to retrieve objects from a realm.

For more information on constructing queries, refer to the Realm Query Language reference documentation.

final team =
realm.query<Team>('name == \$0', ['Millennium Falcon Crew']).first;
final humanCrewMembers = team.crew.query('name != \$0', ['Chewbacca']);

Sort the results using the Realm Query Language SORT() operator in the query() method's argument.

realm.write(() {
realm.addAll([
Person(ObjectId(), 'Luke'),
Person(ObjectId(), 'Leia'),
Person(ObjectId(), 'Han'),
Person(ObjectId(), 'Chewbacca')
]);
});
final alphabetizedPeople =
realm.query<Person>('TRUEPREDICATE SORT(name ASC)');
for (var person in alphabetizedPeople) {
print(person.name);
}
// prints 'Chewbacca', 'Han', 'Leia', 'Luke'

Once you've opened a realm, you can create objects within it using a Realm.write() transaction block.

All operations within a write transaction are atomic. If an operation in the write transaction fails, the whole transaction fails, Realm throws an error, and no changes from the transaction block are applied to the realm.

realm.write((){
// ...write data to realm
});

You can also return values from the write transaction callback function.

final yoda = realm.write<Person>(() {
return realm.add(Person(ObjectId(), 'Yoda'));
});

Warning

Write RealmObjects to One Realm

You can only write RealmObjects to a single realm. If you already wrote a RealmObject to one realm, the SDK throws a RealmException if you try to write it to another realm.

To add an object to a realm, pass an instance of a Realm object class to the realm in a write transaction block with Realm.add().

realm.write(() {
realm.add(Person(ObjectId(), 'Lando'));
});

To add multiple objects to a realm, pass a list of multiple objects to Realm.addAll() inside a write transaction block.

realm.write(() {
realm.addAll([
Person(ObjectId(), 'Figrin D\'an'),
Person(ObjectId(), 'Greedo'),
Person(ObjectId(), 'Toro')
]);
});

To modify an object's properties, update the properties in a write transaction block.

realm.write(() {
spaceshipTeam.name = 'Galactic Republic Scout Team';
spaceshipTeam.crew
.addAll([Person(ObjectId(), 'Luke'), Person(ObjectId(), 'Leia')]);
});

To upsert an object, call Realm.add() with the optional update flag set to true inside a transaction block. The operation inserts a new object with the given primary key if an object with that primary key does not exist. If there's already an object with that primary key, the operation updates the existing object for that primary key.

final id = ObjectId();
// Add Anakin Skywalker to the realm with primary key `id`
final anakin = Person(
id,
"Anakin Skywalker",
);
realm.write(() {
realm.add<Person>(anakin);
});
// Overwrite the 'Anakin' Person object
// with a new 'Darth Vader' object
final darthVader = Person(id, 'Darth Vader');
realm.write(() {
realm.add<Person>(darthVader, update: true);
});

Delete an object from a realm by calling Realm.delete() in a write transaction block.

realm.write(() {
realm.delete(obiWan);
});

Delete multiple objects from a realm the Realm.deleteMany() in a write transaction block.

realm.write(() {
realm.deleteMany([obiWan, quiGon]);
});

Delete all objects of a type in a realm with Realm.deleteAll() in a write transaction block.

realm.write(() {
realm.deleteAll<Person>();
});

You can add, modify, or delete objects asynchronously using Realm.writeAsync().

When you use Realm.writeAsync() to perform write operations, waiting to obtain the write lock and committing a transaction occur in the background. Only the write itself occurs on the main process.

This can reduce time spent blocking the execution of the main process. This is particularly useful when using Device Sync, where you don't know when and for how long the Sync client will be writing.

// Add Leia to the realm using `writeAsync`
Person leia = Person(ObjectId(), "Leia");
realm.writeAsync(() {
realm.add<Person>(leia);
});
←  Configure & Open a Realm - Flutter SDKReact to Changes - Flutter SDK →
Share Feedback
© 2023 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.