Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Realm Database

Reaccione a los cambios - Flutter SDK

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:

  • Query on collection

  • Realm object

  • Colecciones en un objeto Realm

  • User instance

Los ejemplos de esta página utilizan dos tipos de objetos, Character y Fellowship:

@RealmModel()
class _Character {
@PrimaryKey()
late ObjectId id;
late String name;
late String species;
late int age;
}
@RealmModel()
class _Fellowship {
@PrimaryKey()
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
});

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

inserted

List<int>

Indexes in the new collection which were added in this version.

modified

List<int>

Índices de los objetos en la nueva colección que se modificaron en esta versión.

deleted

List<int>

Índices de la versión anterior de la colección que se han eliminado de esta.

newModified

List<int>

Indexes of modified objects after deletions and insertions are accounted for.

moved

List<int>

Indexes of the objects in the collection which moved.

results

RealmResults<T as RealmObject>

Se monitorea la recopilación de resultados para detectar cambios.

isCleared

bool

Returns true if the results collection is empty in the notification callback.

// 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
});

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

isDeleted

bool

true if the object was deleted.

object

RealmObject

Realm object being monitored for changes.

properties

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.
});

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 contiene las siguientes propiedades:

Propiedad
Tipo
Descripción

inserted

List<int>

Índices de los elementos de la lista que se agregaron en esta versión.

modified

List<int>

Indexes of items in the previous version of the list that were modified in this version.

deleted

List<int>

Indexes of items in the previous version of the list that were removed from this version.

newModified

List<int>

Indexes of modified items after deletions and insertions are accounted for.

moved

List<int>

Indexes of the items in the list that moved in this version.

list

Lista de reinos<T>

RealmList siendo supervisado por cambios.

isCleared

booleano

true cuando la lista se ha borrado llamando a su método RealmList.clear().

isCollectionDeleted

booleano

true cuando se ha eliminado el objeto padre que contiene la lista.

RealmSetChanges contiene las siguientes propiedades:

Propiedad
Tipo
Descripción

inserted

List<int>

Índices de los elementos del conjunto que se agregaron en esta versión.

modified

List<int>

Indexes of the items in the previous version of the set that were modified in this version.

deleted

List<int>

Indexes of items in the previous version of the set that were removed from this version.

newModified

List<int>

Indexes of modified items after deletions and insertions are accounted for.

moved

List<int>

Indexes of the items in the set that moved in this version.

set

RealmSet<T>

RealmSet siendo supervisado por cambios.

isCleared

booleano

true cuando el conjunto se ha borrado llamando a su método RealmSet.clear().

isCollectionDeleted

booleano

true when the parent object containing the set has been deleted.

RealmMapChanges contiene las siguientes propiedades:

Propiedad
Tipo
Descripción

inserted

Lista<String>

Keys of the map that were added in this version.

modified

Lista<String>

Keys of the previous version of the map whose corresponding values were modified in this version.

deleted

Lista<String>

Keys of the previous version of the map that were removed from this version.

map

Mapa del reino<T>

RealmMap siendo supervisado por cambios.

isCleared

booleano

true cuando el mapa se ha limpiado llamando a su método RealmMap.clear().

isCollectionDeleted

booleano

true when the parent object containing the map has been deleted.

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`.
});

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

user

Usuario

La instancia de usuario que ha cambiado.

final userSubscription = user.changes.listen((changes) {
changes.user; // the User being listened to
});

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();

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();

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.

Volver

Borrar

En esta página