Todos los objetos del SDK de Flutter son activos, lo que significa que se actualizan automáticamente al modificarse. El SDK emite una notificación cada vez que cambia alguna propiedad.
Cuando un usuario añade un nuevo elemento a una lista, es posible que quieras actualizar la Interfaz de Usuario, mostrar una notificación o registrar un mensaje. Cuando alguien actualiza ese elemento, es posible que quieras cambiar su estado visual o enviar una solicitud de red. Finalmente, cuando alguien borra el elemento, probablemente quieras removerlo de la Interfaz de Usuario. El sistema de notificaciones del SDK te permite observar y reaccionar a los cambios en tus datos, independientemente de las operaciones de guardado que causaron los cambios.
You can subscribe to changes on the following events:
About the Examples on This Page
Los ejemplos de esta página utilizan dos tipos de objetos, Character y Fellowship:
() class _Character { () late ObjectId id; late String name; late String species; late int age; } () class _Fellowship { () late ObjectId id; late String name; late List<_Character> members; }
Additionally, the examples have this sample data:
final frodo = Character(ObjectId(), 'Frodo', 'Hobbit', 51); final samwise = Character(ObjectId(), 'Samwise', 'Hobbit', 39); final gollum = Character(ObjectId(), 'Gollum', 'Hobbit', 589); final aragorn = Character(ObjectId(), 'Aragorn', 'Human', 87); final legolas = Character(ObjectId(), 'Legolas', 'Elf', 2931); final gimli = Character(ObjectId(), 'Gimli', 'Dwarf', 140); final fellowshipOfTheRing = Fellowship( ObjectId(), 'Fellowship of the Ring', members: [frodo, samwise, aragorn, legolas, gimli]); final config = Configuration.local([Fellowship.schema, Character.schema]); final realm = Realm(config); realm.write(() { realm.add(fellowshipOfTheRing); realm.add(gollum); // not in fellowship });
Registrar un oyente
Register a Query Change Listener
Puedes registrar un controlador de notificaciones para cualquier consulta dentro de un dominio. El controlador recibe un mensaje "RealmResultsChanges".objeto, que incluye la descripción de los cambios desde la última notificación. RealmResultsChanges contiene las siguientes propiedades:
Propiedad | Tipo | Descripción |
| List<int> | Indexes in the new collection which were added in this version. |
| List<int> | Índices de los objetos en la nueva colección que se modificaron en esta versión. |
| List<int> | Índices de la versión anterior de la colección que se han eliminado de esta. |
| List<int> | Indexes of modified objects after deletions and insertions are accounted for. |
| List<int> | Indexes of the objects in the collection which moved. |
| RealmResults<T as RealmObject> | Se monitorea la recopilación de resultados para detectar cambios. |
| bool | Returns |
// 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 });
Register a RealmObject Change Listener
You can register a notification handler on a specific object within a realm. Realm notifies your handler when any of the object's properties change. The handler receives a RealmObjectChanges object, which includes description of changes since the last notification. RealmObjectChanges contains the following properties:
Propiedad | Tipo | Descripción |
| bool |
|
| RealmObject | Realm object being monitored for changes. |
| Lista<String> | Nombres de las propiedades del objeto Realm que han cambiado. |
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. });
Register Collection Change Listeners
Cambiado en la versión 1.7.0: Se añadió soporte para RealmMap listeners de cambios.
Changed in version 2.0.0: Added isCollectionDeleted property to collection listeners. Added isCleared property to RealmMapChanges.
You can register a notification handler on a collection of any of the supported data types within another RealmObject. Realm notifies your handler when any of the items in the collection change. The handler receives one of the following objects that include a description of changes since the last notification:
RealmListChanges object for
RealmListCambiosRealmSet objeto para
RealmSetRealmMapChanges object for
RealmMap
RealmListChanges contiene las siguientes propiedades:
Propiedad | Tipo | Descripción |
|---|---|---|
| List<int> | Índices de los elementos de la lista que se agregaron en esta versión. |
| List<int> | Indexes of items in the previous version of the list that were modified in this version. |
| List<int> | Indexes of items in the previous version of the list that were removed from this version. |
| List<int> | Indexes of modified items after deletions and insertions are accounted for. |
| List<int> | Indexes of the items in the list that moved in this version. |
| Lista de reinos<T> |
|
| booleano |
|
| booleano |
|
RealmSetChanges contiene las siguientes propiedades:
Propiedad | Tipo | Descripción |
|---|---|---|
| List<int> | Índices de los elementos del conjunto que se agregaron en esta versión. |
| List<int> | Indexes of the items in the previous version of the set that were modified in this version. |
| List<int> | Indexes of items in the previous version of the set that were removed from this version. |
| List<int> | Indexes of modified items after deletions and insertions are accounted for. |
| List<int> | Indexes of the items in the set that moved in this version. |
| RealmSet<T> |
|
| booleano |
|
| booleano |
|
RealmMapChanges contiene las siguientes propiedades:
Propiedad | Tipo | Descripción |
|---|---|---|
| Lista<String> | Keys of the map that were added in this version. |
| Lista<String> | Keys of the previous version of the map whose corresponding values were modified in this version. |
| Lista<String> | Keys of the previous version of the map that were removed from this version. |
| Mapa del reino<T> |
|
| booleano |
|
| booleano |
|
final fellowshipSubscription = fellowshipOfTheRing.members.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.list; // The full RealmList of objects. changes.isCleared; // `true` after call to fellowshipOfTheRing.members.clear(); otherwise, `false`. changes.isCollectionDeleted; // `true` if the collection is deleted; otherwise, `false`. });
Registrar un Listener de cambios de instancia de usuario
Nueva en la versión 1.9.0.
En la versión 1.9.0 y posteriores de Flutter SDK, puedes registrar un manejador de notificaciones en una instancia específica de User dentro de un realm. Realm notifica a tu manejador cuando cambia alguna de las propiedades del usuario (por ejemplo, si se actualiza el token de acceso del usuario o si cambia el estado del usuario). El manejador recibe un objeto de tipo UserChanges, que incluye la descripción de los cambios desde la última notificación. UserChanges contiene la siguiente propiedad:
Propiedad | Tipo | Descripción |
| Usuario | La instancia de usuario que ha cambiado. |
final userSubscription = user.changes.listen((changes) { changes.user; // the User being listened to });
Pause and Resume a Change Listener
Pausa tu suscripción si temporalmente no quieres recibir notificaciones. Puedes reanudar la escucha más tarde.
subscription.pause(); // The changes.listen() method won't fire until subscription is resumed. subscription.resume();
Unsubscribe a Change Listener
Cancela la suscripción de tu escucha de cambios cuando ya no quieras recibir notificaciones sobre actualizaciones de los datos que está monitoreando.
await subscription.cancel();
Change Notification Limits
Changes in nested documents deeper than four levels down do not trigger change notifications.
If you have a data structure where you need to listen for changes five levels down or deeper, workarounds include:
Refactorice el esquema para reducir la anidación.
Add something like "push-to-refresh" to enable users to manually refresh data.