Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy asset from bundle to file system

Tags:

flutter

dart

I'm trying to copy an sqlite database from the root bundle onto the file system in order to use it.

I've tried many different ways but it always ended up writing incorrect amounts of data to disk. The code I'm using looks like this:

Directory appDocDir = await getExternalStorageDirectory();
String path = join(appDocDir.path, "data.db");
bool exists = await new File(path).exists();
if (!exists) {
  var out = new File(path).openWrite();

  var data = await rootBundle.load("assets/data.sqlite");
  var list = data.buffer.asUint8List();
  out.write(list);
  out.close();
}
like image 203
xen Avatar asked Jan 31 '23 01:01

xen


1 Answers

I was able to do that by the followings.

ByteData data = await rootBundle.load("data.sqlite");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

Directory appDocDir = await getApplicationDocumentsDirectory()
String path = join(appDocDir.path, "data.db");
await File(path).writeAsBytes(bytes);
like image 180
hrsma2i Avatar answered Feb 08 '23 16:02

hrsma2i