Question
When I try to initialize Hive I get this error. Could you please help with what I'm doing wrong?
Code sample
void main() async{
WidgetsFlutterBinding.ensureInitialized();
HiveHelper.init();
runApp(MyApp());
}
class HiveHelper {
static void init() async {
final dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
}
Version
I think you are trying to init before MyApp is built ran, try it after.
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
void main() async {
runApp(MaterialApp(
home: Scaffold(
body: FirstWidget(),
),
));
}
class FirstWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() => FirstState();
}
class FirstState extends State {
@override
void initState() {
super.initState();
HiveHelper.init();
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.lightGreen,
child: Center(
child: Text('Test'),
),
);
}
}
class HiveHelper {
static void init() async {
final dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
print('[Debug] Hive path: ${Hive.path}');
}
}
Most of the examples I found the init was in the main method before calling runApp();
Anyway I tried putting the method inside initState of a page but I got the same error.
Ok I was unable to recreate your error message but I'm on stable channel and you are dev. Maybe that's the difference. Hope you get it working, Hive has worked really well for me so far.
@d-apps have you tried to run the example from @sethchhim or one of the demo apps?
Also please run flutter clean and test it again.
I didn't try the example. I did flutter clean and had the same error. Do you think this is something to do with the channel?
No I don't think it has anything to do with Flutter. I will try to run the sample you shared later but it looks fine to me.
Edit: You need to await the call to HiveHelper.init().
@leisim Thank you, problem solved.
I needed to add await the init method since I am getting that path from path provider I think, and ensure the binding is initialized too.
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await HiveHelper.init();
runApp(MyApp());
}
Most helpful comment
No I don't think it has anything to do with Flutter. I will try to run the sample you shared later but it looks fine to me.
Edit: You need to await the call to
HiveHelper.init().