Home > Software design >  when should I call box.close() in hive flutter, and is it even necessary?
when should I call box.close() in hive flutter, and is it even necessary?

Time:11-30

Working with Hive for Flutter, after I opened my box and been using it, should I call :

box.close()

For closing it while I will still need to use that box, does it affect performance in somehow to let it open, or should I just ignore closing it in my App?

CodePudding user response:

While it can be a good practice to always close a Hive box, you don't actually need to close it if you're willing to re-open it again at some point on your app.

You should close the box when you're completely done working with it in your app since there is no point anymore that it will still open.

box.close();

As from the official Hive docs :

If you don't need a box again, you should close it. All cached keys and values of the box will be dropped from memory and the box file is closed after all active read and write operations are finished.

And :

It is perfectly fine to leave a box open for the runtime of the app. If you need a box again in the future, just leave it open.

So you should not really care about leaving your box open if you still need it, your app will still work fine and with good performance.

If you're experiencing some slow operation on the Hive box when the box data grows, consider using lazyBox instead of box, When a lazyBox is opened, all of its keys are read and stored in memory. Once you access a value, Hive knows its exact position :

await Hive.openLazyBox('myLazyBox');
final lazyBox = Hive.lazyBox('myLazyBox');
final value = await lazyBox.get('lazyVal');

CodePudding user response:

A ticket has already been opened for this question. In the case of framework questions, you can often just look through the issues on github.

  • Related