Quick Start - Flutter SDK
On this page
This page contains information to quickly get Realm Database integrated into your Flutter app.
Before you begin, ensure you have:
The Flutter SDK currently only supports local Realm Database. You cannot use the Flutter SDK to connect to MongoDB Realm application services or use Realm Sync.
Define Your Object Model
Your application's data model defines the structure of data stored within Realm Database. You can define your application's data model via Dart classes in your application code with a Realm object schema. You then have to generate the RealmObject class that's used within your application.
Create Data Model
To define your application's data model, add a Realm model class definition to your application code.
Some considerations when defining your Realm model class:
- Import package at the top of your class definition file.
- In your file, give your class a private name (starting with
_
), such as a filecar.dart
with a class_Car
. You generate the public RealmObject class using the command in the Generate RealmObject Class section. This command outputs a public class, such asCar
. - Make sure to include the generated file name, such as
part car.g.dart
, before the code defining your model. This is required to generate the RealmObject class.
Generate RealmObject Class
Now generate a RealmObject class Car
from the data model class Car
:
Running this creates a Car
class in a car.g.dart
file located in the directory
where you defined the model class per the above Create Data Model section.
This Car
class is public and part of the same library
as the _Car
data model class.
The generated Car
class is what's used throughout your application.
If you'd like to watch your data model class to generate a new Car
class whenever
there's a change to _Car
, run:
Open a Realm
Use the Configuration class to control the specifics of the realm you would like to open, including schema.
Pass your configuration to the Realm constructor to generate an instance of that realm:
var config = Configuration([Car.schema]); var realm = Realm(config);
You can now use that realm instance to work with objects in the database.
Work with Realm Objects
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; });
Query for 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}');
Filter a collection 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 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'
Delete Objects
Delete a car by calling the Realm.delete() method in a write transaction block:
realm.write(() { realm.delete(car); });
Delete multiple cars with the Realm.deleteMany() method in a write transaction block.
realm.write(() { realm.deleteMany(cars); });
React to Changes
Listen and respond to changes to a query, a single object, or a list within an object. The change listener is a Stream that invokes a callback function with an containing changes since last invocation as its argument.
To listen to a query, use RealmResults.changes.listen().
// Listen for changes on whole collection final characters = realm.all<Character>(); final subscription = characters.changes.listen((changes) { changes.inserted; // indexes of inserted objects changes.modified; // indexes of modified objects changes.deleted; // indexes of deleted objects changes.newModified; // indexes of modified objects // after deletions and insertions are accounted for changes.moved; // indexes of moved objects changes.results; // the full List of objects }); // Listen for changes on RealmResults final hobbits = fellowshipOfTheRing.members.query('species == "Hobbit"'); final hobbitsSubscription = hobbits.changes.listen((changes) { // ... all the same data as above });
To listen to a single Realm object, use RealmObject.changes.listen().
final frodoSubscription = frodo.changes.listen((changes) { changes.isDeleted; // if the object has been deleted changes.object; // the RealmObject being listened to, `frodo` changes.properties; // the changed properties });
To listen to a list of Realm objects within another Realm object, use RealmList.changes.listen().
final fellowshipSubscription = fellowshipOfTheRing.members.changes.listen((changes) { changes.inserted; // indexes of inserted Realm objects changes.modified; // indexes of modified Realm objects changes.deleted; // indexes of deleted Realm objects changes.newModified; // indexes of modified Realm objects // after deletions and insertions are accounted for changes.moved; // indexes of moved Realm objects changes.list; // the full RealmList of Realm objects });
You can pause and resume subscriptions as well.
subscription.pause(); // the changes.listen() method won't fire until the subscription is resumed subscription.resume();
Once you've finished listening to changes, close the change listener to prevent memory leaks.
await subscription.cancel();
Close a Realm
Once you've finished working with a realm, close it to prevent memory leaks.
realm.close();
Further Examples
For further examples of all the Flutter SDK methods described above and more, refer to the Realm Dart Samples Github repo.