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
/ /
Device Sync - Flutter SDK

Abrir un Realm sincronizado - Flutter SDK

This page describes how to open a synced realm using Device Sync. To learn how to open and configure non-synced realms, see Open and Close a Realm.

Before you open a realm with Flexible Sync in a Flutter application:

  1. Configura Flexible Sync en el backend. Debes configurar Flexible Sync en el backend antes de poder usarlo con tu aplicación cliente.

  2. Initialize the App client.

  3. Authenticate a user in your client project.

Para abrir un reino sincronizado, pase un usuario que haya iniciado sesión, una lista de esquemas de objetos de reino y argumentos nombrados opcionales adicionales a Configuration.flexibleSync()constructor. Este constructor devuelve una FlexibleSyncConfiguration. Luego, pase el FlexibleSyncConfiguration A Realm() para abrir una instancia del dominio. Los datos se sincronizan con App Services en segundo plano después de abrir el dominio.

final currentUser = await app.logIn(credentials);
final config = Configuration.flexibleSync(currentUser, [Tricycle.schema],
path: 'flex.realm');
final realm = Realm(config);

Once you open a synced realm, configure and manage the sync subscriptions.

Para sincronizar todos los datos con aplicación Services cuando abras un realm, usa el método asíncrono Realm.open(). La operación sincroniza todos los datos disponibles antes de devolver el realm.

On first open, Realm.open() downloads all data that matches your sync subscriptions. Subsequent opens only download the latest changes. Depending on initial realm size and updates to the data set while the device is not syncing, performance may be slower on first open and faster on subsequent opens.

If the client application is offline, Realm.open() does not resolve. You should check if the device is connected to the internet before using Realm.open(). If the device is not connected to the internet, you can still use Realm() to open a realm immediately and sync data in the background when an internet connection is available.

// Helper function to check if device is connected to the internet.
Future<bool> isDeviceOnline() async {
// ...logic to check if device is online
}
final config = Configuration.flexibleSync(currentUser, [Tricycle.schema]);
// Only use asynchronous open if app is online.
late Realm realm;
if (await isDeviceOnline()) {
// If the device is online, download changes and then open the realm.
realm = await Realm.open(config);
} else {
// If the device is offline, open the realm immediately
// and automatically sync changes in the background when the device is online.
realm = Realm(config);
}

Para rastrear el estado de la sincronización, pase un ProgressCallback al argumento opcional onProgressCallback llamado.

double progressEstimate = -1;
final realm = await Realm.open(config, onProgressCallback: (syncProgress) {
progressEstimate = syncProgress.progressEstimate;
print('Sync progress: ${progressEstimate * 100}% complete.');
if (progressEstimate == 1.0) {
// Transfer is complete
}
});

Tip

Si desea configurar notificaciones de progreso después de abrir un reino, use SyncSession.getProgressStream.

Para cancelar una sincronización en curso, pase una instancia de CancellationToken al argumento cancellationToken opcional. Llame a CancellationToken.cancel() para cancelar la sincronización.

final token = CancellationToken();
// Cancel the open operation after 30 seconds.
// Alternatively, you could display a loading dialog and bind the cancellation
// to a button the user can click to stop the wait.
Future<void>.delayed(
const Duration(seconds: 30),
() => token.cancel(CancelledException(
cancellationReason: "Realm took too long to open")));
// If realm does not open after 30 seconds with asynchronous Realm.open(),
// open realm immediately with Realm() and try to sync data in the background.
late Realm realm;
try {
realm = await Realm.open(config, cancellationToken: token);
} on CancelledException catch (err) {
print(err.cancellationReason); // prints "Realm took too long to open"
realm = Realm(config);
}

Ejemplo

Realm() vs. Realm.open()

This section compares examples of scenarios when you might want to use Realm() versus Realm.open() to open a realm in an application.

Considera una aplicación que permita a los usuarios registrar y guardar sus recetas favoritas. Quizás quieras darle al usuario la opción de crear una nueva receta sin esperar a descargar actualizaciones, o incluso si está sin conexión. En este caso, Realm() es preferible. El usuario puede operar sin conexión, pero la aplicación sincroniza sus recetas cuando vuelve a tener conexión a la red.

Consideremos una aplicación de juego con versiones para tableta y teléfono. Un usuario juega tanto en una mesa como en un teléfono. Avanza tres niveles en la tableta. Posteriormente, abre el juego en un teléfono. En este caso, Realm.open() es una mejor manera de abrir el reino. Dado que Realm.open() sincroniza los datos antes de devolver el reino, garantiza que el progreso del usuario esté sincronizado en el teléfono antes de empezar a usar la aplicación, incluso si el tiempo de carga inicial puede ser más lento.

For more information on general realm configuration options, refer to Configure a Realm.

To handle errors in your synced realm using additional configuration properties, refer to Handle Sync Errors.

Once you've finished working with a synced realm, close it to prevent memory leaks.

realm.close();
  • Manage Sync Subscriptions: Learn how to add, modify, and remove sync subscriptions once you've opened a synced realm.

  • Manage Sync Session: Learn how to manage the state of the sync session, including pausing and resuming syncing, monitoring upload and download progress, and checking the network connection.

  • Sync Data from Multiple Processes: Learn how to sync data from multiple processes with a single realm.

Volver

Add Sync to an App

En esta página