skip to Main Content

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

2

Answers


  1. 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());
    }
    
    Login or Signup to reply.
  2.  void main() async {
     WidgetsFlutterBinding.ensureInitialized();//add this line to 
     //ensure Initialized
     await Hive.initFlutter();
     await Hive.openBox('mybox');
     runApp(MyApp());
     }
    

    WidgetsFlutterBinding

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search