【发布时间】:2023-01-03 15:36:11
【问题描述】:
我有一个将数据插入数据库的 Flutter 应用程序。 它从数据库中获取并显示数据。
但我得到了一个 *延迟初始化错误.
我认为原因在于 >
静态后期数据库_database;
错误 :
E/flutter ( 6700): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception:
LateInitializationError: Field '_database@29391942' has not been initialized.
代码:
class ProductDBHelper{
static final _databaseName = 'mydb.db';
static final _databaseVersion = 1;
static final _table_products = 'products';
static late String path;
ProductDBHelper._privateConstructor();
static final ProductDBHelper instance = ProductDBHelper._privateConstructor();
static late Database _database;
//// Check whether the database created or not.
Future get database async{
if(_database != null) return _database;
_database = await _initDatabase();
print('Database : $_database');
return _database;
}
//// Initialise database with local file path , db name.
_initDatabase() async{
Directory documentDirectory = await getApplicationDocumentsDirectory();
//// localstorage path/databasename.db
String path = join(documentDirectory.path , _databaseName);
return await openDatabase(
path,
version: _databaseVersion,
onCreate: _onCreate);
}
//// on Create for creating database.
Future _onCreate(Database db, int version) async{
await db.execute('CREATE TABLE $_table_products(id INTEGER PRIMARY KEY autoincrement, name TEXT, price TEXT, quantity INTEGER)');
}
static Future getFileData(){
return getDatabasesPath().then((value)
{
return path = value;
}
);
}
Future insertProduct(Product product) async{
Database db = await instance.database;
return await db.insert(
_table_products, Product.toMap(product),
conflictAlgorithm: ConflictAlgorithm.ignore
);
}
谁能建议我解决这个错误?
【问题讨论】:
标签: database flutter dart dart-null-safety sqflite