How to Manage Multiple Isar Database Instances in a Flutter App?

422 views Asked by At

I am currently developing a Flutter application and I am using Isar as the database solution. In my app, I have two distinct sets of collections/schemas: one that is shared across the entire app, and another that is specific to a certain part of the application.

I am trying to figure out if it's possible to build two separate Isar database instances for these collections. Specifically, I have a few questions:

  1. Do i need to close one instance of Isar before opening and using another one? Or can multiple instances coexist without interfering with each other? 1.1 I've had experienced this issue IsarError: Transaction does not match Isar instance even knowing for sure the instance in question was the correct one.
  2. Are there any best practices or considerations to keep in mind when working with multiple database instances in Isar?

The isar version im using is the latest one atm: 3.1.0+1

1

There are 1 answers

0
bkpk004 On

According to your question you want to create more than one isar database instance

ok just open new instance

 final dir = await getApplicationDocumentsDirectory();
final isar1 = await Isar.open([isar1Schema],
    directory: dir.path,);
 final isar2 = await Isar.open([isar2Schema],
    directory: dir.path,);
  await isar1.writeTxn(() async {
     await isar.isar1model.put(your data...);
      });
   await isar2.writeTxn(() async {
     await isar.isar2model.put(your data...);
      });

assuming you have isar1Schema ,isar2Schema class

According to creator You don't need to close the instance. This is only required if you get a copy of your instance in a background isolate. Then you have to close this copy when the isolate exits. check this link-enter link description here but there is also an easy way to do this just create multiple collection and use in same instance

  final dir = await getApplicationDocumentsDirectory();
final isar = await Isar.open([ContactModelSchema,ChatEntityLocalModelSchema],
    directory: dir.path,);


    await isar.writeTxn(() async {
     await isar.contactModels.put(your data...);
     await isar.chatEntityLocalModels.put(your data....);
      });

here we can use same instance for multiple schema