Load Hive from flutter assets
It's a pain to copy assets files to the app directory before opening them with Hive.
Is there anyways to load using an asset path directly?
I'm happy to implement in a PR if you have a solution in mind.
It is important that every box has a file where changes can be stored.
I can't think of a way to avoid copying a box file from the assets to an actual directory.
We could implement something like this in the hive_flutter package but I'm not sure if that's a good idea.
I would create a helper method for your app.
I found a solution, but not directly.
- first: I copied existing hive file
mac2factory.hiveinto my assets folder, and define it inpubspec.yaml, like above:assets/mac2factory.hive - second: I load
mac2factory.hivein flutter by usingPlatformAssetBundle().load;;;final mac2factoryByte = await PlatformAssetBundle().load('assets/mac2factory.hive'); - third: open target file in flutter app while runnig
var applicationDocumentsDirectory = await getApplicationDocumentsDirectory();File file = File('${applicationDocumentsDirectory.path}/mac2factory.hive'); - four: write
mac2factoryBytefile, it's byteData type, so:
await file.writeAsBytes(mac2factoryByte.buffer.asUint8List(mac2factoryByte.offsetInBytes, mac2factoryByte.lengthInBytes));
I could do this for now, can't find any solution.
If you need to read only the content you can use the following:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
final bytesDatabase = await rootBundle.load('hive/database.hive');
await Hive.openBox('database', bytes: bytesDatabase.buffer.asUint8List());
runApp(const MyApp());
}
This will create a copy of the database in assets to getApplicationDocumentsDirectory().
It was tested on Android, Web and Windows.