Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HiveError: Box not found error on hot restart or build in Flutter

I have this code which starts the app build in error but when hot reloaded app works again if I hot restart error occurs again .I have initialized the Box and app works just fine after hot reload but not hot restart or if built in debug mode.

main

void main() async {
  await Hive.initFlutter();

  Hive.openBox('mybox');
  runApp(MyApp());
}

HomePage.dart

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 class _HomePageState extends State<HomePage> {
      final _myBox = Hive.box('mybox');


void writeData() {
      if (_keyText.text.isEmpty || _valueText.text.isEmpty) {
        if (_keyText.text.isEmpty) {
          result = 'Key cannot be null';
          _keyTextNode.requestFocus();
        } else {
          result = 'Value cannot be null';
          _valueTextNode.requestFocus();
        }
      } else {
        _myBox.put(_keyText.text, _valueText.text);
        result =
            '${_keyText.text} : ${_valueText.text} has been saved to HiveBox';
        emptyTextFields();
      }

      setState(() {
        result = result;
      });
    }

>Solution :

the openBox is asynchronous, you need to wait for the box until it’s opened before you use it, add await:

 void main() async {
  await Hive.initFlutter();
  await Hive.openBox('mybox'); // add await
  runApp(MyApp());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading