正如标题中的问题所说。
我的数据库文件可能非常大,所以我不想不必要地复制它,我当然也不想在原地构建它。
如果db文件是flutter Assets ,sqlite有办法直接访问吗?
我看到了一些建议,我应该将 Assets 的原始数据复制到一个文件中,然后再访问它,但这会浪费存储空间。或者我可以删除 Assets 吗?
有没有一种简单的方法将数据库部署为 Assets 以外的东西,即作为原始文件?
最佳答案
iOS(我认为是 Android?)将要求您首先将文件复制到应用程序的工作目录中。这是标准做法,它是在 protected 文件系统中工作的一部分。如果以某种方式在您的应用程序包(认为这是原始的“主”)和应用程序文档文件夹(“工作副本”)中都有副本是一个交易 killer ,我想您也可以在初始应用程序启动时从服务器下载它,但是……时间就是金钱。
不过,这确实没什么大不了的。为此,请确保通过您的 pubspec.yaml 文件将文件包含在应用程序包中:
flutter:
assets:
- assets/stored_data.db
然后,在打开数据库之前,将其从 app bundle 复制到您的文档目录:
Edit: The following apparently fails to copy large files; see iKK's comment below if you experience such issues, as it looks like he's found a native solution. For smaller files, however, this should work fine.
// Create a new file within your document directory (Probably want to check whether it already exists first...)
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "working_data.db");
ByteData data = await rootBundle.load(join("assets", "stored_data.db"));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await new File(path).writeAsBytes(bytes);
现在您的应用程序文档目录中已经有了数据库,您应该可以从 path 中打开它。
如果您使用的是 tekartik/sqflite包(这是我最初获得这些说明的地方),例如,您可以简单地:
Database db = await openDatabase(path); // Opens SQL database, working_data.db
没有理由(或能力)从应用程序包中删除原始副本(这会改变原始二进制文件 - 巨大 nono)。最终,操作系统本身可能会最终将这些垃圾卸载到云服务器或其他内存管理服务,但这是由平台决定的。
https://stackoverflow.com/questions/48236252/
相关文章:
android - Flutter中如何检测ListView的滚动位置
dart - Flutter - 为什么 slider 不会在 AlertDialog 中更新?
flutter - 用容器包装脚手架以获得渐变背景,如何在 flutter 中将渐变设置为容器背景?
csv - Flutter:如何从简单的电子表格中读取数据?
git - 如何解决 Flutter 上的 "Unable to find git in your
flutter - BottomAppBar float 操作按钮缺口/插图不透明