一、添加第三方庫
flutter pub add sqflite_common_ffi
二瓦灶、在pubspec.yaml中配置assets
注意格式
assets:
- assets/xxx.db
三廉丽、初始化數(shù)據(jù)庫
項(xiàng)目初始化以后會(huì)從根目錄下的.dart_tool/sqflite_common_ffi/databases/xxx.db讀取數(shù)據(jù)庫文件,如果沒有則把a(bǔ)ssets目錄下的拷貝到該目錄下梧兼。
initialDatabase() async {
sqfliteFfiInit();
var databaseFactory = databaseFactoryFfi;
var databasesPath = await databaseFactory.getDatabasesPath();
var path = join(databasesPath, "express.db");
print(path);
var exists = await databaseFactory.databaseExists(path);
if (!exists) {
// Should happen only the first time you launch your application
print("Creating new copy from asset");
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
// Copy from asset
ByteData data = await rootBundle.load('assets/express.db');
print(join('assets','express.db'));
// ByteData data = await rootBundle.load(join('assets','express.db'));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Write and flush the bytes written
await File(path).writeAsBytes(bytes, flush: true);
} else {
print("Opening existing database");
}
// open the database
this._db = await databaseFactory.openDatabase(path);
print(databasesPath);
}
四萝挤、查詢數(shù)據(jù)
// 查詢
Future<List<UnitPrice>> queryPrice() async {
List<UnitPrice> priceList = [];
var result = await _db.query(table_name, where: 'id = ?', whereArgs: [1]);
return priceList;
}