10

I am using this function to make sure to open and close box appropriately but i am still getting HiveError: Box has already been closed. error

static Future<Box<dynamic>> openIt() async {
    var connectionBox = await Hive.openBox(hiveBox);
    if (Hive.isBoxOpen(hiveBox) == false) {
      await Hive.openBox(hiveBox);
     
    } else {
      await connectionBox.close();
      connectionBox = await Hive.openBox(hiveBox);
      
    }

    return connectionBox;
  } 

How can i resolve this issue.

leftjoin
  • 36,950
  • 8
  • 57
  • 116
Bilal Rabbi
  • 1,602
  • 2
  • 18
  • 39

3 Answers3

0

I don't really know why, but using that method without the static keyword and running it fixed it for me.

static Future<Box<dynamic>> openIt() async { // no

Future<Box<dynamic>> openIt() async { // yes
Gwhyyy
  • 7,554
  • 3
  • 8
  • 35
0

I think "Hive.isBoxOpen" is unnecessary code in your function.

And I change a few things in your code;

static Future<Box<dynamic>> openIt() async {
  var connectionBox = Hive.box<dynamic>(hiveBox);
  if (!connectionBox.isOpen) {
    connectionBox = await Hive.openBox<dynamic>(hiveBox);
  }

  return connectionBox;
}

Cloud you try this function?

secret
  • 742
  • 1
  • 7
  • 24
0

According to official HiveDocs

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.

and

Before your application exits, you should call Hive.close() to close all open boxes. Don't worry if the app is killed before you close Hive, it doesn't matter.

So don't always close the box. Only close it on application exit or SignOut, depending on the scenario.

jawad111
  • 11
  • 2