vivek yadav
vivek yadav

Reputation: 1547

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

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

Upvotes: 17

Views: 18968

Answers (4)

Yuriy N.
Yuriy N.

Reputation: 6107

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.

Upvotes: 1

Imran Sefat
Imran Sefat

Reputation: 773

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");

Upvotes: 1

lomza
lomza

Reputation: 9716

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();
 }
}

Upvotes: 2

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4764

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

await Hive.openBox("boxname");

before using the box.

Upvotes: 23

Related Questions