[英]Flutter: I still get the error "Null check operator used on a null value" on the value I made Nullable
static Database? _db;
if (_db != null) {
return;
}
try {
String _path = await getDatabasesPath() + 'users.db';
_db =
await openDatabase(_path, version: _version, onCreate: (db, version) {
print("Database oluşturuldu");
});
} catch (e) {
print(e);
}
}
static Future<List<Map<String, dynamic>>> query() async {
print("query");
return await _db!.query(_tableName);
}
我收到错误Null check operator used on a null value
,即使我将_db
值设为可为空。
感谢有人可以提供建议。 先感谢您!
Nullable 仅仅意味着一个变量可以有一个空值。 与。 您假设此时变量不是 null,因此您可以调用该方法,但是当然,如果您现在没有在 object 中分配值。 然后它将尝试调用 null 值的方法。
在尝试进行查询之前,在代码中的某处初始化数据库 object。
static Database? _db;
//database was never initialized, null by default in this instance
static Future<List<Map<String, dynamic>>> query() async {
print("query");
//you attempt to get the value from a null object while casting it as non null
return await _db!.query(_tableName);
}
您必须先初始化 null 值,然后再使用符号 (.)
return (await _db?.query(_tableName)) ?? [];
这将失败,但不会抛出空指针异常
您可以在 null 案例上返回空列表或再次获取,使用!
仅当您确定该值不是 null 时。 最好先进行 null 检查。
static Future<List<Map<String, dynamic>>> query() async {
print("query");
final result = await _db?.query(_tableName);
if (result == null) {
print("got null db"); // you can reinitialize the db
return [];
} else {
return result;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.