Home > front end >  Flutter Hive Box not found error on first run, but it works fine after I reload the app
Flutter Hive Box not found error on first run, but it works fine after I reload the app

Time:05-22

I have two Hive Boxes as below. I always face this error when I build the app for the first time.

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

However, if I reload the app, it works perfectly fine. Here is the code in my main func where I open the hive boxes. I wonder what is causing that error. I don't want my user to restart the app after installing it for the first time.

void main() async {
      WidgetsFlutterBinding.ensureInitialized();
    
      await Hive.initFlutter();
      await Hive.openBox("User");
      await Hive.openBox("dateData");
    
      runApp(const SplashPage());
    }

CodePudding user response:

you need to initialize hive before using it see this image to see how to do that.

CodePudding user response:

FutureBuilder will do wonder for you,

why it is better to use FutureBuilder for Hive?

When we initialize Hive, it loads all data from the memory, and may take time, till then we must show some kind of animation/loader to user, otherwise your app look like it's freez.

Example:

Scaffold(
      body: FutureBuilder(
        future: Hive.openBox('box_name'),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Center(
                  child: Text(snapshot.error.toString()),
              );
            } else
              return Page1();
          } else {
            return Center(
                child: CircularProgressIndicator(),
            );
          }
        },
      ),
    )
  • Related