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

Time:01-09

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

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

CodePudding user response:

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

CodePudding user response:

 void main() async {
 WidgetsFlutterBinding.ensureInitialized();//add this line to 
 //ensure Initialized
 await Hive.initFlutter();
 await Hive.openBox('mybox');
 runApp(MyApp());
 }

WidgetsFlutterBinding

  • Related