Esta página contiene información para integrar rápidamente Realm en tu aplicación Flutter.
Antes de comenzar, asegúrese de tener:
Define tu modelo de objeto
El modelo de datos de su aplicación define la estructura de los datos almacenados en Realm. Puede definir el modelo de datos de su aplicación mediante clases Dart en el código de su aplicación con un esquema de objetos Realm. A continuación, debe generar el RealmObjectBase clase que se utiliza dentro de su aplicación.
For more information, refer to Define a Realm Object Schema.
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.
En su archivo, asigne a su clase un nombre privado (que comience con
_), como un archivocar.dartcon una clase_Car. La clase pública RealmObject se genera mediante el comando de la sección "Generar clase RealmObject". Este comando genera una clase pública, comoCar.Make sure to include the generated file name, such as
part car.realm.dart, before the code defining your model. This is required to generate the RealmObject class.
import 'package:realm/realm.dart'; part 'car.realm.dart'; () class _Car { () late ObjectId id; late String make; late String? model; late int? miles; }
import 'package:realm_dart/realm.dart'; part 'car.realm.dart'; () class _Car { () late ObjectId id; late String make; late String? model; late int? miles; }
Generate RealmObject Class
Now generate a RealmObject class Car from the data model class Car:
dart run realm generate
dart run realm_dart generate
Running this creates a Car class in a car.realm.dart file located in the directory where you defined the model class per the preceding 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.
Si desea ver cómo su clase de modelo de datos genera una nueva clase Car cada vez que haya un cambio en _Car, ejecute:
dart run realm generate --watch
dart run realm_dart generate --watch
Abrir un reino
Utiliza la clase Configuration para controlar los detalles del realm que deseas abrir, incluido el esquema y si el realm es solo local o sincronizado.
Pasa tu configuración al constructor de Realm para generar una instancia de ese realm:
final config = Configuration.local([Car.schema]); final realm = Realm(config);
You can now use that realm instance to work with objects in the database.
For more information, refer to Configure and Open a Realm.
Trabajar con objetos de Realm
Una vez que hayas abierto un realm, puedes crear objetos dentro de él usando un bloque de transacción de escritura.
Para obtener más información, consulta Transacciones de escritura
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(ObjectId(), 'Tesla', model: 'Model S', miles: 42); realm.write(() { realm.add(car); });
Actualizar objetos
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:
final cars = realm.all<Car>(); final myCar = cars[0]; print('My car is ${myCar.make} ${myCar.model}');
Filtra una colección para recuperar un segmento específico de objetos con el Realm.query() método. En el argumento del método query(), use operadores del Lenguaje de Consulta Realm para realizar filtrado.
final cars = realm.query<Car>('make == "Tesla"');
Borrar objetos
Delete a car by calling the Realm.delete() method in a write transaction block:
realm.write(() { realm.delete(car); });
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 accounting for deletions & insertions. changes.moved; // Indexes of moved objects. changes.results; // The full List of objects. changes.isCleared; // `true` after call to characters.clear(); otherwise, `false`. }); // Listen for changes on RealmResults. final hobbits = fellowshipOfTheRing.members.query('species == "Hobbit"'); final hobbitsSubscription = hobbits.changes.listen((changes) { // ... all the same data as above });
También puedes pausar y reanudar las suscripciones.
subscription.pause(); // The changes.listen() method won't fire until subscription is resumed. subscription.resume();
Once you've finished listening to changes, close the change listener to prevent memory leaks.
await subscription.cancel();
For more information, refer to React to Changes.
Close a Realm
Once you've finished working with a realm, close it to prevent memory leaks.
realm.close();
Sync Realm with MongoDB Atlas
Puedes integrar Realm y Atlas Device Sync en tu aplicación Flutter. Atlas Device Sync es un aplicación Service de MongoDB Atlas que sincroniza datos entre una aplicación cliente y un clúster de base de datos MongoDB en Atlas.
Para sincronizar datos con Atlas utilizando Device Sync, el SDK de Flutter utiliza Flexible Sync. Flexible Sync permite definir una query para los datos que sincronizas desde la aplicación cliente.
Nota
You do not need to add Device Sync to use Realm locally.
Requisitos previos
Before you can use Device Sync with Realm in your client app, you must configure Device Sync using Atlas App Services:
Habilitar sincronización
owner_idflexible. Establecer como campo consultable.Define las reglas que determinan los permisos que tienen los usuarios al usar Device Sync. En este ejemplo, asignamos un rol predeterminado, que se aplica a cualquier colección que no tenga un rol específico. En este ejemplo, un usuario puede leer y escribir datos donde el
user.iddel usuario conectado coincide con elowner_iddel objeto:{ "roles": [ { "name": "owner-read-write", "apply_when": {}, "document_filters": { "write": { "owner_id": "%%user.id" }, "read": { "owner_id": "%%user.id" } }, "read": true, "write": true, "insert": true, "delete": true, "search": true } ] }
Ahora, implemente las actualizaciones de su aplicación.
Tip
Use Realm Flutter Template App
If you want a working Flutter app with Device Sync already set up in the client and on that App Service backend, use the Flutter Template App flutter.todo.flex.
Initialize App Services
To use App Services features such as authentication and sync, access your App Services App using your App ID. You can find your App ID in the App Services UI.
final app = App(AppConfiguration(appId));
Para más información, consulta Conectar a Servicios de aplicación.
Authenticate a User
Después de habilitar la autenticación anónima en la interfaz de usuario de App Services, los usuarios pueden iniciar sesión inmediatamente en su aplicación sin proporcionar ninguna información de identificación:
final loggedInUser = await app.logIn(Credentials.anonymous());
For more information, refer to Authenticate a User.
Open a Synced Realm
Once you have enabled Device Sync and authenticated a user, open a synced realm with Configuration.flexibleSync(). Then, pass the configuration to Realm() to open an instance of the realm. The synced realm must have a different Configuration.path from other opened local-only realms.
final config = Configuration.flexibleSync(loggedInUser, [Todo.schema]); final realm = Realm( config, );
For more information, refer to Open a Synced Realm.
Add a Sync Subscription
Now create a subscription to synchronize data with Atlas using Device Sync. Add the subscription within the SubscriptionSet.update() callback function.
La función de retorno del bloque de actualización incluye un objeto MutableSubscriptionSet() como argumento. Utiliza MutableSubscriptionSet.add() para agregar una nueva suscripción.
// Check if the subscription already exists before adding final userTodoSub = realm.subscriptions.findByName('getUserTodos'); if (userTodoSub == null) { realm.subscriptions.update((mutableSubscriptions) { // server-side rules ensure user only downloads their own Todos mutableSubscriptions.add(realm.all<Todo>(), name: 'getUserTodos'); }); }
For more information, refer to Manage Sync Subscriptions.
Más ejemplos y próximos pasos
Para comenzar con una aplicación Flutter prediseñada usando el SDK de Realm y un backend de Atlas App Services configurado, use la aplicación de plantilla
flutter.todo.flexFlutter,.Para una experiencia guiada de agregar el SDK de Realm con Device Sync a una aplicación de Flutter, consulta el Tutorial de Realm Flutter SDK.
For further examples of the Flutter SDK methods described above and more, refer to the Realm Dart Samples Github repo.