在Flutter中是否有任何预先填充的数据库用法示例? 我不需要CRUD示例。此时,我只需要从数据库读取数据即可。 我是Flutter的新手,所以逐步教程会很不错。
答案 0 :(得分:0)
您可以将您的应用程序与预先填充的sqlite数据库捆绑在assets
文件夹中。然后在第一次运行时,将数据库从资产复制到应用程序的工作目录。下面的代码示例显示了一种实现方法(打印语句仅用于显示发生的情况):
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
Future<Database> initDatabase() async {
var databasesPath = await getDatabasesPath();
var path = join(databasesPath, "app.v1.db");
// Check if the database exists
var exists = await databaseExists(path);
if (!exists) {
// Should happen only the first time you launch your application
print("Creating new copy from asset");
// Make sure the parent directory exists
try {
await Directory(dirname(path)).create(recursive: true);
} catch (e) {
print(e.toString());
}
// Copy from asset
ByteData data = await rootBundle.load(join("assets", "prepopulated.db"));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Write and flush the bytes written
await File(path).writeAsBytes(bytes, flush: true);
print("Database created successfully");
} else {
print("Opening existing database");
}
// open the database
return await openDatabase(path, version: "1", readOnly: false);
}