Read & Write Data - Flutter SDK
On this page
Read from Realm Database
A read from a realm generally consists of the following steps:
- Get all objects of a certain type from the realm.
- Optionally, filter the results using the Realm Query Language.
- Optionally, sort the results using Realm Query Language.
Query All Objects
Retrieve a collection of all objects of a data model in the realm with the Realm.all() method.
var cars = realm.all<Car>(); var myCar = cars[0]; print('My car is ${myCar.make} ${myCar.model}');
Query List of RealmObjects
You can query any list of RealmObjects. For more information on querying, see Filter Results.
final config = Configuration([Person.schema, Team.schema]); final realm = Realm(config); final heroes = Team('Millenium Falcon Crew', crew: [ Person('Luke'), Person('Leia'), Person('Han'), Person('Chewbacca') ]); realm.write(() => realm.add(heroes)); final lukeAndLeia = (heroes.crew).query(r'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 operators to perform filtering.
var cars = realm.all<Car>().query('make == "Tesla"');
Sort Results
Sort the results using the Realm Query Language
SORT() operator in the query()
method's argument.
realm.write(() { realm.add(Car('BMW', model: 'Z4', miles: 42)); realm.add(Car('Audi', model: 'A8', miles: 99)); realm.add(Car('Mercedes', model: 'G-Wagon', miles: 2)); }); final sortedCars = realm.query<Car>('TRUEPREDICATE SORT(model ASC)'); for (var car in sortedCars) { print(car.model); } // prints 'A8', 'G-Wagon', 'Z4'
Write Operations
Once you've opened a realm, you can create objects within it using a write transaction block.
Create Objects
To create a new Car
, instantiate an instance of the
Car
class and add it to the realm in a write transaction block:
final car = Car('Tesla', model: 'Model S', miles: 42); realm.write(() { realm.add(car); });
Update Objects
To modify a car, update its properties in a write transaction block:
realm.write(() { car.miles = 99; });
Delete Objects
Delete a Single Object
Delete a car by calling the Realm.delete() method in a write transaction block:
realm.write(() { realm.delete(car); });
Delete Multiple Objects
Delete multiple cars with the Realm.deleteMany() method in a write transaction block.
realm.write(() { realm.deleteMany(cars); });