hive icon indicating copy to clipboard operation
hive copied to clipboard

Load Hive from flutter assets

Open bolasim opened this issue 7 years ago • 3 comments

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.

bolasim avatar Sep 02 '19 04:09 bolasim

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.

simc avatar Sep 02 '19 09:09 simc

I found a solution, but not directly.

  • first: I copied existing hive file mac2factory.hive into my assets folder, and define it in pubspec.yaml, like above: assets/mac2factory.hive
  • second: I load mac2factory.hive in flutter by using PlatformAssetBundle().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 mac2factoryByte file, 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.

ershat-dl avatar Apr 19 '21 01:04 ershat-dl

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.

olegbilovus avatar Aug 21 '23 01:08 olegbilovus