Reputation: 345
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());
}
Upvotes: 2
Views: 1485
Reputation: 383
I encountered the same issue you described. I was using two Hive boxes, and on the app's initial run, data written to a box would return null when read. Subsequent builds functioned as expected.
No errors were reported, and the code appeared correct. After extensive debugging, I discovered the solution:
Hive boxes require distinct and specified data types when using multiple boxes. Different box names alone are insufficient and can lead to this peculiar error.
To illustrate, here's the corrected code:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
await Hive.openBox<DataType1>("User");
await Hive.openBox<DataType2>("dateData");
runApp(const SplashPage());
}
Upvotes: 0
Reputation: 345
I have fixed it using try{}catch(){}
error handling as shown below. the project was nearly due and I couldn't find any better solution but this works perfect. Here is the code.
void addData() async {
try{
Box<dynamic> data = Hive.box("boxName");
}catch(error){
await Hive.openBox("boxName");
addData();
}
}
Upvotes: 0
Reputation: 34210
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(),
);
}
},
),
)
Upvotes: 1
Reputation: 259
you need to initialize hive before using it see this image to see how to do that.
Upvotes: 0