You might want to seed your mobile app with some initial data that will be available to users on the initial launch of the app. To do this, you can bundle an existing realm file in your Flutter app.
Si tu aplicación usa un dominio sincronizado, es posible que no quieras agruparlo. Para obtener más información, consulta Agrupa una sección de Reino sincronizado.
Tip
Consider Initial Data Callback
You can also add data to your realm the first time an application opens it using the initial data callback function.
Agrupar un reino local
Crear un archivo de reino para agrupar
Create a new project with the same Realm object schema as your production app. Open an existing realm with the data you wish to bundle, or create a new one.
Obtenga la ruta al archivo del reino con Realm.config.path propiedad.
print("Bundling realm"); final config = Configuration.local([Car.schema], path: 'bundle.realm'); final realm = Realm(config); realm.write(() { realm.add(Car(ObjectId(), "Audi", model: 'A8')); realm.add(Car(ObjectId(), "Mercedes", model: 'G Wagon')); }); print("Bundled realm location: " + realm.config.path); realm.close();
Tip
Crear un dominio agrupado con el SDK independiente de Dart
You might want to use the Dart Standalone SDK to create the bundled realm for your Flutter application for the following reasons:
Creating a bundled realm does not require any Flutter UI elements.
Los proyectos autónomos de Dart requieren menos código repetitivo que los proyectos de Flutter.
Incluya un archivo Realm en su aplicación de producción
Ahora que tiene una copia del reino con los datos "semilla" en él, debe empaquetarlo con su aplicación de producción.
Añade el archivo realm a los recursos de Flutter de tu aplicación. Por ejemplo, podrías añadir el archivo realm incluido en tu proyecto, en la assets/bundled.realm ubicación.
Add a reference to the bundled realm to your pubspec.yaml file to include it in your production application:
flutter: assets: - realm/bundle.realm
Open a Realm from a Bundled Realm File
Now that you have a copy of the realm included with your app, you need to add code to use it.
Before you deploy your app with the bundled realm, you need to extract the realm from the embedded resources, save it to the app's data location, and then open this new realm in the app. The following code shows how you can do this during start-up of the app.
Crear una función auxiliar initBundledRealm Para comprobar si el dominio incluido ya existe en la aplicación y cargarlo si aún no existe. Llama a initBundledRealm antes de llamar a la función de carga de los widgets de la aplicación con runApp().
// Also import Realm schema and Flutter widgets import 'package:flutter/services.dart'; import 'package:realm/realm.dart'; import 'dart:io'; Future<Realm> initBundledRealm(String assetKey) async { final config = Configuration.local([Car.schema]); final file = File(config.path); if (!await file.exists()) { final realmBytes = await rootBundle.load(assetKey); await file.writeAsBytes( realmBytes.buffer .asUint8List(realmBytes.offsetInBytes, realmBytes.lengthInBytes), mode: FileMode.write); } return Realm(config); } void main() async { WidgetsFlutterBinding.ensureInitialized(); final realm = await initBundledRealm("assets/bundle.realm"); runApp(const MyApp()); }
Bundle a Synced Realm
En la mayoría de los casos, no deberías incluir un realm sincronizado. Si el realm incluido se actualizó por última vez hace más tiempo que el tiempo máximo de desconexión del cliente, el usuario experimenta un restablecimiento del cliente la primera vez que abre el archivo Realm incluido. El restablecimiento del cliente hace que la aplicación descargue el estado completo del realm desde el backend de la aplicación. Esto anula las ventajas de incluir un archivo realm.
Rather than bundling a synced realm, you can populate your application with data using sync subscriptions. If you add data using sync subscriptions, you do not need to be concerned with data being older than the client maximum online time while taking advantage of Flexible Sync's trimming feature. To learn more about using sync subscriptions, refer to Manage Sync Subscriptions.
You should only bundle a synced realm if your use case meets the following criteria:
Puede asegurarse de que los usuarios tengan una versión de la aplicación con el reino sincronizado incluido que se creó más recientemente que el tiempo máximo sin conexión del cliente.
Los datos iniciales incluidos son muy grandes y la aplicación se está utilizando en una situación con un ancho de banda de Internet limitado, por lo que una descarga de datos inicial mediante suscripciones de sincronización tomaría demasiado tiempo.
Todos los usuarios de la aplicación tienen permiso del backend para ver los datos incluidos en el paquete. Si un usuario no tiene permiso para ver estos datos, se eliminarán de su dispositivo cuando el dominio se sincronice con Atlas mediante un error de escritura compensatorio.
To bundle a synced realm, perform the following:
Connect to your App Services App and authenticate a user.
Add a subscription to the realm. You need a subscription to write to a synced realm.
Agrega datos al realm sincronizado.
Espere a que todos los cambios locales se sincronicen con el servidor de sincronización del dispositivo.
Use Realm.writeCopy() to create a new version of the synced realm. You must use
Realm.writeCopy()to bundle the synced realm because the method removes metadata that associates the realm with the user, which allows other users to open the realm file as well.
print("Bundling synced realm"); // You must connect to the Device Sync server with an authenticated // user to work with the synced realm. final app = App(AppConfiguration(APP_ID)); // Check if current user exists and log anonymous user if not. final user = app.currentUser ?? await app.logIn(Credentials.anonymous()); final config = Configuration.flexibleSync(user, [Car.schema]); final realm = Realm(config); // Add subscription that match the data being added // and your app's backend permissions. realm.subscriptions.update((mutableSubscriptions) { mutableSubscriptions.add(realm.all<Car>()); }); await realm.subscriptions.waitForSynchronization(); // Add data to realm realm.write(() { realm.add(Car(ObjectId(), "Audi", model: 'A8')); realm.add(Car(ObjectId(), "Mercedes", model: 'G Wagon')); }); // Sync changes with the server await realm.syncSession.waitForUpload(); await realm.syncSession.waitForDownload(); // Create new configuration for the bundled realm. // You must specify a path separate from the realm you // are copying for Realm.writeCopy() to succeed. final bundledConfig = Configuration.flexibleSync(user, [Car.schema], path: 'sync_bundle.realm'); realm.writeCopy(bundledConfig); print("Bundled realm location: " + bundledConfig.path); realm.close();
Después de crear el realm empaquetado, sigue las instrucciones de las secciones anteriores Agrupa un archivo Realm en tu aplicación de producción y Abre un Realm desde un archivo de Realm empaquetado.