Realm Dart & Flutter SDK

repository·main·Indexed 21 days ago

https://github.com/realm/realm-dart

A mobile-first, object-oriented database for Dart and Flutter applications. It provides SDKs for iOS, Android, Windows, macOS, and Linux, featuring a CLI for native binary installation and code generation for RealmObject classes. Supports local database operations, querying, and observation, as well as integration with Atlas App Services for Device Sync (deprecated as of September 2024).

Tokens
20.7K
Snippets
82
Records
96
Agent score
73%

What's inside realm-dart

  1. Query and Observe Realm Objects

    main

    Realm provides several ways to retrieve data and react to changes:

    • Retrieve all objects: Use realm.all<T>() to get all instances of a type.
    • Query with filters: Use .query() with a string expression. You can use positional arguments (e.g., $0) to prevent injection and handle dynamic values.
    • Find by Primary Key: Use realm.find<T>(id) to retrieve a specific object.
    • Observe changes: Use the .changes property on a result set to listen to a stream of updates (insertions, deletions, and modifications).
    // Querying
    var cars = realm.all<Car>().query("make == 'Tesla'");
    var carsWithArgs = realm.all<Car>().query(r'make == $0', ['Tesla']);
    
    // Finding by Primary Key
    var myCar = realm.find<Car>(0);
    
    // Observing changes
    final carsStream = realm.all<Car>().query(r'make == $0', ['Tesla']);
    carsStream.changes.listen((changes) {
      print('Inserted: ${changes.inserted}');
      print('Deleted: ${changes.deleted}');
      print('Modified: ${changes.modified}');
    });
  2. Quickstart: Define, Generate, and Use Realm Models

    main

    To use Realm, you follow a three-step process: define a data model, generate the concrete RealmObject class, and then interact with the database using a Realm instance.

    1. Define the Model: Create a class starting with an underscore (e.g., _Car) and annotate it with @RealmModel(). Use late for required properties.
    2. Generate the Class: Run the generator command to create the concrete class (e.g., Car) and the required .realm.dart part file.
    3. Use the Model: Open a Realm instance with a Configuration.local containing your schema, and perform operations within realm.write() blocks.
    import 'package:realm/realm.dart';
    
    part 'app.realm.dart';
    
    @RealmModel()
    class _Car {
      late String make;
      late String model;
      int? kilometers = 500;
    }
    
    // After running 'dart run realm generate':
    var config = Configuration.local([Car.schema]);
    var realm = Realm(config);
    
    var car = Car("Tesla", "Model Y", kilometers: 5);
    realm.write(() {
      realm.add(car);
    });
  3. Setup a Realm Dart SDK command-line application

    main

    To set up a Dart application using the Realm Dart SDK, follow these steps to fetch dependencies, install native binaries, and generate the necessary RealmObject classes.

    1. Fetch dependencies: Run dart pub get to install the project dependencies.
    2. Install native binaries: Run dart run realm_dart install. This step is critical as it downloads and copies the required native binaries into your application directory.
    3. Generate RealmObject classes: Run dart run realm_dart generate. This command creates the generated code file (e.g., bin/myapp.g.dart) based on your Realm models.
    4. Run the app: Use dart run to execute the application.
    dart pub get
    dart run realm_dart install
    dart run realm_dart generate
    dart run
  4. Use realm_example to learn the Realm SDK for Flutter

    main
    The realm_example project serves as a demonstration application for using the Realm SDK within a Flutter environment. It provides a practical starting point for developers looking to integrate Realm's mobile database capabilities into a Flutter application.
  5. Install the realm_dart dev CLI helper

    main

    The realm_dart repository includes a CLI helper tool designed for development tasks. You can install it using one of two methods:

    1. Using Melos: If the project is managed with Melos, run melos setup from the repository root.
    2. Using Dart Pub: Navigate to the directory containing this README and run the dart pub global activate command pointing to the local path.

    Note: Ensure that ~/.pub_cache/bin is included in your system's PATH environment variable to run the activated tool.

    dart pub global activate --source path .
  6. Install Realm Dart on Windows

    main

    Due to a bug in the Dart VM on Windows regarding how native extension binaries are located, Realm Dart requires a manual installation step to ensure the native .dll is placed in the correct path.

    To resolve this, run the following command from the root directory of your Dart application:

    dart pub run realm_dart install

    Note: The documentation refers to pub run realm_dart install, which is the legacy syntax for dart pub run realm_dart install.

  7. Set up Atlas App Services for Device Sync

    main

    To use Realm Device Sync, you must first configure your backend on MongoDB Atlas:

    1. Create an account: Register at cloud.mongodb.com.
    2. Create an App: Use the Atlas App Services UI to create a new application.
    3. Configure Authentication: Set up an Authentication Provider (e.g., Anonymous, Email/Password).
    4. Enable Flexible Sync: Navigate to the Device Sync menu in the Atlas UI and Enable Flexible Sync.
    5. Retrieve App ID: Locate and copy your application's unique App ID.
  8. Setup Realm Flutter SDK

    main

    To use Realm in a Flutter application:

    1. Add the package:
      flutter pub add realm
    2. Install native binaries (required for running Flutter widget and unit tests):
      dart run realm install

    Requirements:

    • Flutter 3.10.2 or newer.
    • iOS: Cocoapods v1.11 or newer.
    • Desktop: CMake 3.21 or newer.
    • Supported Platforms: iOS, Android, Windows, MacOS, and Linux.
    flutter pub add realm
    dart run realm install
  9. Setup Realm Dart Standalone SDK

    main

    To use Realm in a pure Dart application:

    1. Add the package:
      dart pub add realm_dart
    2. Install native binaries (downloads and copies required binaries to the app directory):
      dart run realm_dart install

    Requirements:

    • Dart SDK 3.0.2 or newer.
    • Supported Platforms: Windows, Mac, and Linux.
    dart pub add realm_dart
    dart run realm_dart install
  10. Use Device Sync with Realm Flutter and Dart

    main

    To synchronize data between a local Realm and Atlas App Services, follow these three steps:

    1. Initialize and Authenticate: Create an App instance using your appId and log in a user (e.g., using Credentials.anonymous()).
    2. Open a Synced Realm: Use Configuration.flexibleSync(user, [schema]) to create a realm configuration that links to your authenticated user and specific object schemas.
    3. Manage Subscriptions and Write Data: Use realm.subscriptions.update to define which data subsets should be synced to the device. Only data matching these queries will be downloaded. Always call await realm.subscriptions.waitForSynchronization() before performing writes to ensure the subscription state is established.
    // 1. Initialize and Authenticate
    String appId = "<Atlas App ID>";
    final appConfig = AppConfiguration(appId);
    final app = App(appConfig);
    final user = await app.logIn(Credentials.anonymous());
    
    // 2. Open a synced realm
    final config = Configuration.flexibleSync(user, [Task.schema]);
    final realm = Realm(config);
    
    // 3. Add a sync subscription and write data
    realm.subscriptions.update((mutableSubscriptions) {
      mutableSubscriptions.add(realm.query<Task>(r'status == $0 AND progressMinutes == $1', ["completed", 100]));
    });
    await realm.subscriptions.waitForSynchronization();
    
    realm.write(() {
      realm.add(Task(ObjectId(), "Send an email", "completed", 4));
      realm.add(Task(ObjectId(), "Create a meeting", "completed", 100));
      realm.add(Task(ObjectId(), "Call the manager", "init", 2));
    });
    
    realm.close();