A few years later from the accepted answer, objectbox now has an additional function that can work well with an isolate.
This is the Store.attach() function. Using this function, you can attach a store by providing the database path without having to worry about a separate isolate closing the store:
The actual underlying store is only closed when the last store instance is closed (e.g. when the app exits).
In my own case, I had to use the workmanager package to execute a background task that depends on the objectbox store.
You can create an "initializer" class like so:
class ObjectBox {
static late final Store store;
static Future initialize() async {
var docsDir = await getApplicationDocumentsDirectory();
var dbPath = p.join(docsDir.path, "objectbox");
if (Store.isOpen(dbPath)) {
store = Store.attach(getObjectBoxModel(), dbPath);
} else {
store = await openStore(directory: dbPath);
}
}
}
Once you have this, you can then use the initialize() in your isolate. Example with the workmanager package:
main.dart
@pragma("vm:entry-point")
void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData) async {
await ObjectBox.initialize(); // Initialize in background isolate.
return true;
});
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await ObjectBox.initialize(); // Initialize in main isolate
Workmanager().initialize(callbackDispatcher);
runApp(const MyApp());
}
This way, even if you close the database in your main isolate, the background isolate will still continue to function. The underlying store itself is closed once all store instances are closed.