I get a weird error when trying to initialize Hive
Solution 1
Hive needs to be initialized when it runs on Android or iOS, therefore you can use a function like this:
Future<Box> openHiveBox(String boxName) async {
if (!kIsWeb && !Hive.isBoxOpen(boxName))
Hive.init((await getApplicationDocumentsDirectory()).path);
return await Hive.openBox(boxName);
}
You'll need to import path_provider in order to access getApplicationDocumentsDirectory()
Solution 2
Try the following code on the main function of your flutter application:
import 'package:path_provider/path_provider.dart';
import 'package:hive/hive.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocumentDirectory = await getApplicationDocumentsDirectory();
Hive.init(appDocumentDirectory.path);
}
mck
A chemist who loves Spark :) If you find my answers helpful, I'd appreciate a cup of coffee!
Updated on December 27, 2022Comments
-
mck over 1 year
Error:
Unhandled Exception: HiveError: You need to initialize Hive or provide a path to store the box.
Essentially I have these in my dependencies so everything should be good.
hive: ^1.4.4+1 hive_flutter: ^0.3.1 path_provider: ^1.6.27
I also have
import 'package:hive/hive.dart';
andimport 'package:path_provider/path_provider.dart';
in the fileSo I just have
void doSomething() async { final documentDirectory = await getApplicationDocumentsDirectory(); Hive.init(documentDirectory.path); }
called.
I do not understand. I think I've done everything correct. Let me know if you need something else.