14

When working with HIVE database in flutter. If you ever get error like this:

"Box not found. Did you forget to call Hive.openBox()?"

It means you haven't opened your box to

To resolve this issue call

await Hive.openBox("boxname");

before using the box

vivek yadav
  • 1,367
  • 2
  • 12
  • 16
  • Plesae find ans in question – vivek yadav Dec 21 '19 at 14:11
  • 1
    When you post a question, it gives you the option to answer your question. Make sure to check that and you should post an answer at least to make it clear that it's answered. Make sure to mark it as accepted. – Benjamin Dec 21 '19 at 14:25

4 Answers4

20

It means you haven't opened your box. To resolve this issue call

await Hive.openBox("boxname");

before using the box.

Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
1

You have to open the box you want to use and make sure to use await while using the openBox() function.

await Hive.openBox("boxname");
Imran Sefat
  • 528
  • 4
  • 6
0

The box needs to be open either at the beginning, after database initialization or right before doing the operation on the box.

For example in my AppDatabase class I have only one box ('book') and I open it up in the initialize() method, like below:

The whole application and tutorial is here.

const String _bookBox = 'book';

@Singleton()
class AppDatabase {
  AppDatabase._constructor();

  static final AppDatabase _instance = AppDatabase._constructor();

  factory AppDatabase() => _instance;

  late Box<BookDb> _booksBox;

  Future<void> initialize() async {
    await Hive.initFlutter();
    Hive.registerAdapter<BookDb>(BookDbAdapter());
    _booksBox = await Hive.openBox<BookDb>(_bookBox);
  }

  Future<void> saveBook(Book book) async {
    await _booksBox.put(
    book.id,
    BookDb(
      book.id,
      book.title,
      book.author,
      book.publicationDate,
      book.about,
      book.readAlready,
    ));
  }

  Future<void> deleteBook(int id) async {
    await _booksBox.delete(id);
  }

  Future<void> deleteAllBooks() async {
    await _booksBox.clear();
 }
}
lomza
  • 9,412
  • 15
  • 70
  • 85
0

I got this exception because I moved Hive initialization in a separate function and called it without await.

It was like this (working):

void main() async {
  await Hive.initFlutter();
  await Hive.openBox('box');
  runApp(
    const ProviderScope(child: MainApp()),
  );
}

Became like this (exception):

void main() async {
  initHive();  // should be await initHive();
  runApp(
    const ProviderScope(child: MainApp()),
  );
}
initHive() async {
    await Hive.initFlutter();
    await Hive.openBox('box');
}

Without await the application does not wait for Future to complete and tries to look inside the box which is not yet opened.

Yuriy N.
  • 4,936
  • 2
  • 38
  • 31