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

Configurar y abrir un Realm - Flutter SDK

Usa el Configuración clase para controlar los detalles del reino que desea abrir, incluido el esquema.

Para crear un dominio que solo persista datos localmente, cree una configuración con Configuration.local(). Debe proporcionar una lista de esquemas como argumento.

Pasar el Configuration al constructor del reino.

final config = Configuration.local([Car.schema]);
final realm = Realm(config);

You can now use that realm instance to work with objects in the database.

To open a realm that synchronizes data with Atlas using Device Sync, refer to Open a Synced Realm.

To create a realm that runs in memory without being persisted, create your Configuration with Configuration.inMemory(). You must provide a list of schemas as an argument. In-memory realms cannot also be read-only.

Pass the Configuration to the Realm constructor.

final config = Configuration.inMemory([Car.schema]);
final realm = Realm(config);

Puedes añadir propiedades opcionales al Configuration del realm.

Puedes abrir un dominio existente en modo de solo lectura. Para ello, añade readOnly: true a tu objeto Configuration.

Solo puedes abrir reinos existentes en modo de solo lectura. Si intentas escribir en un realm de solo lectura, se producirá un error.

final config = Configuration.local([Car.schema], isReadOnly: true);
final realm = Realm(config);

Establece un valor para la ubicación de archivos especiales FIFO de Realm. Abrir un Realm crea una serie de archivos especiales FIFO livianos que coordinan el acceso al Realm a través de hilos y procesos. Si el archivo Realm está en una ubicación que no permite la creación de archivos especiales FIFO (como los sistemas de archivos FAT32), entonces el Realm no puede abrirse. En este caso, Realm necesita una ubicación diferente para almacenar estos archivos. Agrega fifoFilesFallbackPath: <Your Custom FIFO File Path> a tu objeto Configuration.

Esta propiedad se ignora si el directorio del archivo realm permite archivos especiales FIFO.

final config = Configuration.local([Car.schema],
fifoFilesFallbackPath: "./fifo_folder");
final realm = Realm(config);

Use initialDataCallback() to invoke a callback function the first time that you open a realm. The function only executes the first time you open that realm on the device. The realm instance passed to the callback function already has a write transaction open, so you do not need to wrap write operations in a Realm.write() transaction block. initialDataCallback can be useful for adding initial data to your application the first time that it is opened on a device.

void dataCb(Realm realm) {
realm.add(Car(ObjectId(), 'Honda'));
}
final config =
Configuration.local([Car.schema], initialDataCallback: dataCb);
final realm = Realm(config);
Car honda = realm.all<Car>()[0];

You can customize the default path where Realm stores database files and the default name given to database files.

Use the static Configuration.defaultRealmName and Configuration.defaultRealmPath to set default configuration for all realms opened within an application.

Configuration.defaultRealmName = "myRealmName.realm";
final customDefaultRealmPath = path.join(
(await Directory.systemTemp.createTemp()).path,
Configuration.defaultRealmName);
Configuration.defaultRealmPath = customDefaultRealmPath;
// Configurations used in the application will use these values
final config = Configuration.local([Car.schema]);
// The path is your system's temp directory
// with the file named 'myRealmName.realm'
print(config.path);

You can also check where realm stores the files by default using the static getter Configuration.defaultStoragePath. The value for this property varies depending on the platform you are using the SDK on and whether you are using the Dart or Flutter versions of Realm. Check the value of Configuration.defaultStoragePath in your application to see where realm files are stored in your environment.

final storagePath = Configuration.defaultStoragePath;
// See value in your application
print(storagePath);

For more information about managing schema changes when configuring a realm, refer to the Update a Realm Object Schema documentation.

You can encrypt your local realm to ensure data security. For more information, see Encrypt a Realm.

You can reduce the local realm file size to improve performance and manage file size in a resource-constrained environment. For more information, refer to Compact a Realm.

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

realm.close();

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

realm.close();

Si ejecutas una aplicación CLI de Dart, para evitar que el proceso quede colgado, llama a Realm.shutdown()

Realm.shutdown();

Para copiar datos de un reino existente a un nuevo reino con diferentes opciones de configuración, pase la nueva configuración a Realm.writeCopy().

In the new realm's configuration, you must specify the path. You cannot write to a path that already contains a file.

Usando Realm.writeCopy(), puedes convertir entre los siguientes tipos de Configuración:

  • LocalConfiguration to LocalConfiguration

  • FlexibleSyncConfiguration to FlexibleSyncConfiguration

  • InMemoryConfiguration to InMemoryConfiguration

  • LocalConfiguration to read-only LocalConfiguration and vice versa

  • InMemoryConfiguration to LocalConfiguration and vice versa

  • FlexibleSyncConfiguration to LocalConfiguration

  • FlexibleSyncConfiguration to InMemoryConfiguration

No puedes convertir de un LocalConfiguration o de un InMemoryConfiguration a un FlexibleSyncConfiguration.

Algunas consideraciones adicionales a tener en cuenta al utilizar Realm.writeCopy():

  1. El archivo de destino no puede existir ya.

  2. Copying a realm is not allowed within a write transaction or during migration.

  3. When using Device Sync, you must sync all local changes with the server before the copy is written. This ensures that the file can be used as a starting point for a newly-installed application. The Realm.writeCopy() throws if there are pending uploads.

El siguiente ejemplo copia los datos de un reino con un InMemoryConfiguration a un nuevo reino con un LocalConfiguration.

// Create in-memory realm and add data to it.
// Note that even though the realm is in-memory, it still has a file path.
// This is because in-memory realms still use memory-mapped files
// for their operations; they just don't persist data across launches.
final inMemoryRealm =
Realm(Configuration.inMemory([Person.schema], path: 'inMemory.realm'));
inMemoryRealm.write(() {
inMemoryRealm.addAll([Person("Tanya"), Person("Greg"), Person("Portia")]);
});
// Copy contents of `inMemoryRealm` to a new realm with `localConfig`.
// `localConfig` uses the default file path for local realms.
final localConfig = Configuration.local([Person.schema]);
inMemoryRealm.writeCopy(localConfig);
// Close the realm you just copied when you're done working with it.
inMemoryRealm.close();
// Open the local realm that the data from `inMemoryRealm`
// was just copied to with `localConfig`.
final localRealm = Realm(localConfig);
// Person object for "Tanya" is in `localRealm` because
// the data was copied over with `inMemoryRealm.writeCopy()`.
final tanya = localRealm.find<Person>("Tanya");

You can also include a new encryption key in the copied realm's configuration or remove the encryption key from the new configuration.

The following example copies data from an unencrypted realm with a LocalConfiguration to an encrypted realm with a LocalConfiguration.

// Create unencrypted realm and add data to it.
final unencryptedRealm = Realm(Configuration.local([Person.schema]));
unencryptedRealm.write(() => unencryptedRealm.addAll([
Person("Daphne"),
Person("Harper"),
Person("Ethan"),
Person("Cameron")
]));
// Create encryption key and encrypted realm.
final key = List<int>.generate(64, (i) => Random().nextInt(256));
final encryptedConfig = Configuration.local([Person.schema],
path: 'encrypted.realm', encryptionKey: key);
// Copy the data from `unencryptedRealm` to a new realm with
// the `encryptedConfig`. The data is encrypted as part of the copying.
unencryptedRealm.writeCopy(encryptedConfig);
// Close the realm you just copied when you're done working with it.
unencryptedRealm.close();
// Open the new encrypted realm with `encryptedConfig`.
final encryptedRealm = Realm(encryptedConfig);
// Person object for "Harper" is in `localRealm` because
// the data was copied over with `unencryptedRealm.writeCopy()`.
final harper = encryptedRealm.find<Person>('Harper');

Volver

Datos geoespaciales

En esta página