共计 1211 个字符,预计需要花费 4 分钟才能阅读完成。
一、增加第三方库
flutter pub add sqflite_common_ffi
二、在 pubspec.yaml 中配置 assets
留神格局
assets:
- assets/xxx.db
三、初始化数据库
我的项目初始化当前会从根目录下的.dart_tool/sqflite_common_ffi/databases/xxx.db 读取数据库文件,如果没有则把 assets 目录下的拷贝到该目录下。
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);
}
四、查问数据
// 查问
Future<List<UnitPrice>> queryPrice() async {List<UnitPrice> priceList = [];
var result = await _db.query(table_name, where: 'id = ?', whereArgs: [1]);
return priceList;
}
正文完