1

I am building a Flutter app with ObjectBox database.

App calls openStore(); at launch, and saves the Store instance in a singleton class so that I can access to it from anywhere.

But I'm not sure when to call store.close();

In iOS we can execute code right before app termination using applicationWillTerminate(_:)

Unfortunately, Flutter does not provide us something like this.

I tried below code in the longest live expected StatefulWidget but it sometimes dispose sooner and the app loses access to the database.

@override
void dispose() {
  StoreHelper().store?.close();
  super.dispose();
}

My questions are...

  1. What's the best practice to call store.close()?
  2. What happen if I don't close the store? Would my app lose data persistency?
Vincent Gigandet
  • 918
  • 10
  • 21

1 Answers1

3

What you're doing seems OK to me. You could change it up slightly to StoreHelper().close() which would also clear set its Store reference to null, in which case if some other part of the app still tried to access, you could handle that (recognize it's closed or reopen it).

Also, in most cases, you should get away without closing the store explicitly. Unless you're doing (many) background write operations in which case you should probably try to at least wait for it to finish in dispose().

vaind
  • 1,642
  • 10
  • 19
  • "Also, in most cases, you should get away without closing the store explicitly" means that if my app has no background operation then I don't need to close the Store and let user terminate the app with the Store still open? – Vincent Gigandet Jul 20 '21 at 07:39
  • Yes, since you really can't prevent users from terminating the app whenever they want anyway :) – vaind Jul 20 '21 at 08:19
  • Thanks. BTW, the ObjectBox [getting started doc](https://docs.objectbox.io/getting-started) says "don't forget to close the store" in the comment in "Create a Store" section. So I thought I have to. – Vincent Gigandet Jul 20 '21 at 08:34
  • 1
    Good point, we should clarify that in the docs. – Markus Junginger Jul 21 '21 at 18:24