Read & Write Data - Flutter SDK
On this page
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
.
()class _Person { () late ObjectId id; late String name; } ()class _Team { () late ObjectId id; late String name; late List<_Person> crew; }
Read Operations
Find Object by Primary Key
Find an object by its primary key with Realm.find().
final luke = realm.find<Person>(lukePrimaryKey);
Query All Objects
Retrieve a collection of all objects of a data model in the realm with the Realm.all() method.
final people = realm.all<Person>();
Query List of RealmObjects
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 Results
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.
final team = realm.query<Team>('name == \$0', ['Millennium Falcon Crew']).first; final humanCrewMembers = team.crew.query('name != \$0', ['Chewbacca']);
You can use iterable arguments in your filter. For example:
final listOfNames = ['Luke', 'Leia']; final matchingRealmObjects = realm.query<Person>('name IN \$0', [listOfNames]);
For more information on constructing queries, refer to the Realm Query Language reference documentation.
Filter with Full-Text Search
You can use Realm Query Language (RQL) to query on properties that have a
Full-Text Search Index (FTS) annotation.
To query these properties, use the TEXT
predicate in your query.
Exclude results for a word by placing the -
character in front of the word.
For example, a search for -sheep wool
would include all search results for
wool
excluding those with sheep
.
In the following example, we query on the Rug.pattern
and Rug.material
fields:
// Find rugs with a chevron pattern final chevronRugs = realm.query<Rug>("pattern TEXT \$0", ["chevron"]); // Find rugs with a wool material but not sheep wool final notSheepWoolRugs = realm.query<Rug>("material TEXT \$0", [" -sheep wool"]);
Full-Text Search Tokenizer Details
Full-Text Search (FTS) indexes support:
Boolean match word searches, not searches for relevance.
Tokens are diacritics- and case-insensitive.
Tokens can only consist of characters from ASCII and the Latin-1 supplement (western languages).
All other characters are considered whitespace. Words split by a hyphen (-) like full-text are split into two tokens.
For more information on features of the FTS index, see the API reference for RealmIndexType.
Sort Results
Sort query results using the Realm Query Language SORT() operator in the query()
method's argument.
Note that you can't use parameterized queries in RQL SORT() clauses. Instead, use strings or string interpolation.
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'
Limit Results
Limit query results using the Realm Query Language LIMIT() operator in the query()
method's argument.
Note that you can't use parameterized queries in RQL LIMIT() clauses. Instead, use strings or string interpolation.
realm.write(() { realm.addAll([ Person(ObjectId(), 'Luke'), Person(ObjectId(), 'Luke'), Person(ObjectId(), 'Luke'), Person(ObjectId(), 'Luke') ]); }); final limitedPeopleResults = realm.query<Person>('name == \$0 LIMIT(2)', ['Luke']); // prints `2` print(limitedPeopleResults.length);
Write Operations
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.
Create Objects
Create One Object
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')); });
Create Multiple Objects
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') ]); });
Update Objects
Update Object Properties
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')]); });
Upsert Objects
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 Objects
Delete a Single Object
Delete an object from a realm by calling Realm.delete() in a write transaction block.
realm.write(() { realm.delete(obiWan); });
Delete Multiple Objects
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
Delete all objects of a type in a realm with Realm.deleteAll() in a write transaction block.
realm.write(() { realm.deleteAll<Person>(); });
Background Writes
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); });