Query and Observe Realm Objects
mainRealm provides several ways to retrieve data and react to changes:
- Retrieve all objects: Use
realm.all<T>()to get all instances of a type. - Query with filters: Use
.query()with a string expression. You can use positional arguments (e.g.,$0) to prevent injection and handle dynamic values. - Find by Primary Key: Use
realm.find<T>(id)to retrieve a specific object. - Observe changes: Use the
.changesproperty on a result set to listen to a stream of updates (insertions, deletions, and modifications).
// Querying
var cars = realm.all<Car>().query("make == 'Tesla'");
var carsWithArgs = realm.all<Car>().query(r'make == $0', ['Tesla']);
// Finding by Primary Key
var myCar = realm.find<Car>(0);
// Observing changes
final carsStream = realm.all<Car>().query(r'make == $0', ['Tesla']);
carsStream.changes.listen((changes) {
print('Inserted: ${changes.inserted}');
print('Deleted: ${changes.deleted}');
print('Modified: ${changes.modified}');
});