如何在空安全的情况下设置 sqlite 数据库?
How to set up sqlite database in flutter with null safety?
为了在flutter中用sqflite搭建一个sqlite数据库,折腾了好久。每次我为数据库调用 getter 方法时,代码都会生成一个新的数据库实例。这是代码:
class DatabaseProvider {
DatabaseProvider._();
static final DatabaseProvider dbProvider = DatabaseProvider._();
static Database? _database;
Future<Database> get database async => _database ??= await _createDatabase();
}
...
您需要在 getter 中初始化 _database
。因此,将其更改为:
Future<Database> get database async {
if (_database == null) {
// initialize database from _createDatabase result.
_database = await _createDatabase();
}
// because _database have beeen initialized above,
// then we can use ! to tell that the _database can't be null.
return _database!;
}
为了在flutter中用sqflite搭建一个sqlite数据库,折腾了好久。每次我为数据库调用 getter 方法时,代码都会生成一个新的数据库实例。这是代码:
class DatabaseProvider {
DatabaseProvider._();
static final DatabaseProvider dbProvider = DatabaseProvider._();
static Database? _database;
Future<Database> get database async => _database ??= await _createDatabase();
}
...
您需要在 getter 中初始化 _database
。因此,将其更改为:
Future<Database> get database async {
if (_database == null) {
// initialize database from _createDatabase result.
_database = await _createDatabase();
}
// because _database have beeen initialized above,
// then we can use ! to tell that the _database can't be null.
return _database!;
}