Rather than calling some async function to get document directory and initialize hive database inside main
function, I want to keep things as abstract as possible. I want to implement Hive.init(..)
inside a provider service and calling that service during initState()
method. In this way my main
method does not care or even does not know what database I am using, rather than calling the provider service. The implementation should be like this.
service.dart
class Service extends ChangeNotifier {
....
Future<void> init() async {
Directory dir = await getExternalStorageDirectory();
Hive.init(dir.path);
....
view.dart
class MyPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (BuildContext context) => Service(),
child: _MyPageContent(),
);
}
}
.....
class _MyPageContent extends StatefulWidget {
@override
__MyPageContentState createState() => __MyPageContentState();
}
class __MyPageContentState extends State<_MyPageContent> {
@override
void initState() {
super.initState();
Provider.of<Service>(context, listen: false).init();
}
....
....
However, this is not working. The error I am getting as
HiveError (HiveError: You need to initialize Hive or provide a path to store the box.)
The reason may be Service.init()
method, being an async one, is getting called inside initState()
by the time build
method performs it's task. So is there any way to fix this ?