pinchbv / floor

The typesafe, reactive, and lightweight SQLite abstraction for your Flutter applications
https://pinchbv.github.io/floor/
Apache License 2.0
947 stars 190 forks source link

Access database in isolates #786

Open AnilNeodove opened 10 months ago

AnilNeodove commented 10 months ago

i want to use database in seperate isolates but getting error.

databaseFactory is only initialized when using sqflite. When using sqflite_common_ffi You must call databaseFactory = databaseFactoryFfi; before using global openDatabase API

anyone is facing same issue

Riya-Singhal15 commented 3 months ago

Yes I'm facing the same

Riya-Singhal15 commented 3 months ago

Have u resolved it?

Riya-Singhal15 commented 3 months ago

I've resolved it by using the following line in isolate entry function. BackgroundIsolateBinaryMessenger.ensureInitialized(args[1]); And RootIsolateToken

For Expamle

Inside main -
    /// Initialize Isolates
    final rootIsolateToken = RootIsolateToken.instance;
    if (rootIsolateToken == null) {
      Logger.instance.writeLogs("main - rootIsolateToken", "Cannot get the RootIsolateToken", LogLevel.error);
      return;
    }
    await Isolate.spawn(
          dbIsolateEntry, [mainSendPort, rootIsolateToken]);

static void dbIsolateEntry(List<dynamic> args) async {
    final dbReceivePort = ReceivePort();
    final dbSendPort = dbReceivePort.sendPort;
    BackgroundIsolateBinaryMessenger.ensureInitialized(args[1]);

   // initialize database
    await DatabaseProvider().database;
    await for (final BaseIsolateMessage message in dbReceivePort) {
        // listen for messages
     }
}