Importante
Flutter SDK v2.0.0 Breaking Change to Generated Files
La versión 2.0.0 del SDK de Flutter introduce una actualización del compilador que afecta la generación de archivos. En la versión2.0.0 y posteriores, todos los archivos generados usan .realm.dart convención de nombres en lugar de .g.dart.
This is a breaking change for existing apps. For information on how to upgrade an existing app from an earlier SDK version to v2.0.0 or later, refer to Upgrade to Flutter SDK v2.0.0.
An object schema is a configuration object that defines the properties and relationships of a Realm object. Realm client applications define object schemas with the native class implementation in their respective language using the Object Schema.
Los esquemas de objetos especifican restricciones sobre las propiedades de un objeto, como el tipo de datos de cada propiedad y si una propiedad es obligatoria o no. Los esquemas también pueden definir relaciones entre tipos de objetos en un realm.
Create Model
Directiva de creación de parte de archivo generado
Cambiado en la versión v2.0.0: Los archivos generados se denominan .realm.dart en lugar de .g.dart
Añade una directiva de parte para incluir el archivo RealmObject que generaste en el paso 4 en el mismo paquete que el archivo en el que estás trabajando actualmente.
part 'schemas.realm.dart';
Create RealmModel
Crea el modelo para tu esquema de Realm. Debes incluir la anotación. Modelo de reino en la parte superior de la definición de clase.
You'll use the RealmModel to generate the public RealmObject used throughout the application in step 4.
You can make the model private or public. We recommend making the all models private and defining them in a single file. Prepend the class name with an underscore (_) to make it private.
Si necesita definir su esquema en varios archivos, puede hacer público el RealmModel. Anteponga el nombre con un signo de dólar ($) para que el modelo sea público. Debe hacer esto para generar el RealmObject a partir del RealmModel, como se describe en el paso 4.
Add fields to the RealmModel. You can add all supported data types. Include additional behavior using property annotations.
() class _Car { () late ObjectId id; late String make; late String? model; late int? miles; }
Nota
Class names are limited to a maximum of 57 UTF-8 characters.
Generate RealmObject
Cambiado en la versión v2.0.0: Los archivos generados se denominan .realm.dart en lugar de .g.dart
Generate the RealmObject, which you'll use in your application:
dart run realm generate
dart run realm_dart generate
This command generates the file in the same directory as your model file. It has the name you specified in the part directive of step 2.
Tip
Seguimiento del archivo generado
Rastrear el archivo generado en tu sistema de control de versiones, como git.
Ejemplo
File structure after generating model
. ├── schemas.dart ├── schemas.realm.dart // newly generated file ├── myapp.dart └── ...rest of application
Use RealmObject in Application
Use the RealmObject that you generated in the previous step in your application. Since you included the generated file as part of the same package where you defined the RealmModel in step 2, access the RealmObject by importing the file with the RealmModel.
import './schemas.dart'; final hondaCivic = Car(ObjectId(), 'Honda', model: 'Civic', miles: 99);
Using Schemas with Device Sync
An App Services Schema is a list of valid object schemas that each define an object type that an App may persist. All synced objects in a realm must conform to the App Services Schema.
Client applications provide a Object Schema when they open a realm. If a realm already contains data, then it already has a schema, and when it is opened, Realm validates the schema on the client against the existing schema.
You can define App Services Schemas in the following ways:
Automáticamente con el Esquema de objetos si el modo de desarrollo está habilitado.
Explicitly define the App Services Schema with App Services.
In your schema you must use the MapTo("_id") annotation with your primary key in the RealmModel to successfully sync your Object Schema with App Services.
() class _SyncSchema { () ("_id") late ObjectId id; // ... other properties }
For further information on defining your schema and which of these approaches you should consider for your application, refer to the Create a Realm Schema documentation.
Tipos de datos admitidos
Los esquemas de Realm admiten muchos tipos de datos en el lenguaje Dart, además de algunos tipos específicos de Realm. Para una referencia completa de todos los tipos de datos admitidos, consulta Tipos de datos.
Property Annotations
Utiliza anotaciones para añadir funcionalidades a las propiedades en tus modelos de objetos Realm. Puede usar anotaciones para cosas como marcar una propiedad como nullable, establecer una clave primaria, ignorar una propiedad y más. Para obtener más información sobre las anotaciones de propiedades disponibles, consulta Anotaciones de Propiedades.
Definir propiedades de relación
You can define relationships between Realm objects in your schema. The Realm Flutter SDK supports to-one relationships, to-many relationships, inverse relationships, and embedding objects within other objects. To learn more about how to define relationships in your Realm object schema, refer to Relationships.
Map a Model or Class to a Different Name
Puede usar la anotación MapTo para asignar un modelo de objeto o propiedad de Realm a un nombre almacenado diferente en Realm. Esto puede ser útil en los siguientes casos. Por ejemplo:
Para facilitar el trabajo entre plataformas donde las convenciones de nomenclatura difieren. Por ejemplo, si los nombres de las propiedades del esquema de Device Sync usan snake case, mientras que tu proyecto usa camel case.
To change a class or field name without forcing a migration.
To support multiple model classes with the same name in different packages.
To use a class name that is longer than the 57-character limit enforced by Realm.
Si está utilizando Atlas Device Sync, el nombre que especifique en la MapTo anotación se utilizará como nombre de esquema de App Services persistente.
() ('naval_ship') class _Boat { () late ObjectId id; late String name; late int? maxKnots; late int? nauticalMiles; }
class _Vehicle { () late ObjectId id; late String? maybeDescription; // optional value late double milesTravelled = 0; // 0 is default value () late String notInRealmModel; () late String make; ('wheels') // 'wheels' is property name in the RealmObject late int numberOfWheels; }
Modelar datos no estructurados
Nuevo en la versión 2.0.0.
Starting in Flutter SDK version 2.0.0, you can store collections of mixed data within a RealmValue property. You can use this feature to model complex data structures, such as JSON or MongoDB documents, without having to define a strict data model.
Unstructured data is data that doesn't easily conform to an expected schema, making it difficult or impractical to model to individual data classes. For example, your app might have highly variable data or dynamic data whose structure is unknown at runtime.
Storing collections in a mixed property offers flexibility without sacrificing functionality, including performant synchronization when using Device Sync. And you can work with them the same way you would a non-mixed collection:
Se pueden anidar colecciones mixtas hasta 100 niveles.
You can query on and react to changes on mixed collections.
You can find and update individual mixed collection elements.
However, storing data in mixed collections is less performant than using a structured schema or serializing JSON blobs into a single string property.
Para modelar datos no estructurados en tu aplicación, define las propiedades adecuadas en tu esquema como tipos RealmValue. Luego puedes configurar estas RealmValue propiedades como una colección RealmList o una colección RealmMap de RealmValue elementos. Tenga en cuenta que RealmValue no puede representar un RealmSet ni un objeto incrustado.
For example, you might use a RealmValue that contains a map of mixed data when modeling a variable event log object:
// Define class with a `RealmValue` property () class _EventLog { () late ObjectId id; late String eventType; late DateTime timestamp; late String userId; late RealmValue details; }
realm.write(() { // Add `eventLog` property data as a map of mixed data, which // also includes nested lists of mixed data realm.add(EventLog(ObjectId(), 'purchase', DateTime.now(), 'user123', details: RealmValue.from({ 'ipAddress': '192.168.1.1', 'items': [ {'id': 1, 'name': 'Laptop', 'price': 1200.00}, {'id': 2, 'name': 'Mouse', 'price': 49.99} ], 'total': 1249.99 }))); final eventLog = realm.all<EventLog>().first; final items = eventLog.details.asMap(); print(''' Event Type: ${eventLog.eventType} Timestamp: ${eventLog.timestamp} User ID: ${eventLog.userId} Details: Item: '''); for (var item in items.entries) { print('${item.key}: ${item.value}'); }
Event Type: purchase Timestamp: 2024-03-18 13:50:58.402979Z User ID: user123 Details: Item: ipAddress: RealmValue(192.168.1.1) items: RealmValue([RealmValue({id: RealmValue(1), name: RealmValue(Laptop), price: RealmValue(1200.0)}), RealmValue({id: RealmValue(2), name: RealmValue(Mouse), price: RealmValue(49.99)})]) total: RealmValue(1249.99)
Tip
Use a map of mixed data types when the type is unknown but each value will have a unique identifier.
Utilice una lista de tipos de datos mixtos cuando el tipo sea desconocido, pero el orden de los objetos sea importante.
Generar el RealmObject
Cambiado en la versión v2.0.0: Los archivos generados se denominan .realm.dart en lugar de .g.dart
Once you've completed your Realm model, you must generate the RealmObject class to use it in your application.
Run the following command to generate RealmObjects:
dart run realm generate
dart run realm_dart generate
Ejecutar esto crea una clase pública en un nuevo archivo en el directorio donde definiste la clase RealmModel según la sección Crear modelo.
El archivo generado tiene el mismo nombre base que el archivo con su RealmModel, terminando en .realm.dart. Por ejemplo, si el archivo con su RealmModel se llama schemas.dart, el archivo generado será schemas.realm.dart.
Nota
Remember to include the generated file in a part directive in your RealmModel definition file.
// ...import packages part 'schemas.realm.dart'; () // ...model definition
Si quiere observar tus modelos de datos para generar RealmObjects cada vez que haya un cambio, incluye la bandera --watch en tu comando.
dart run realm generate --watch
dart run realm_dart generate --watch
To clean the generator caches, include the --clean flag in your command. Cleaning the generator cache can be useful when debugging.
dart run realm generate --clean
dart run realm_dart generate --clean
Definir un objeto asimétrico
New in version 1.5.0.
Asymmetric objects require Flexible Sync. To define an asymmetric object, pass ObjectType.asymmetricObject to @RealmModel().
(ObjectType.asymmetricObject) class _WeatherSensor { () ("_id") late ObjectId id; late String deviceId; late double modtemperatureInFahrenheitel; late double barometricPressureInHg; late double windSpeedInMph; }
In Flutter SDK versions 1.5.0 and earlier, you cannot link from asymmetricObject types to RealmObjects. In SDK versions 1.6.0 and later, asymmetricObject types can link to RealmObjects in addition to embedded object types.
Nota
Attempting to Read Asymmetric Objects
No se pueden leer objetos asimétricos. Si intentas query un objeto asimétrico, obtendrás el siguiente error: "Error: no puedes query una clase asimétrica.".
Para obtener más información sobre Data Ingest, consulta Transmitir datos a Atlas.