为什么这个 Dart 代码给出 "The operand can't be null, so the condition is always true. Remove the condition"?

why does this Dart code give "The operand can't be null, so the condition is always true. Remove the condition"?

为什么这段Dart代码给出“操作数不能为null,所以条件总是为真。去掉条件”?

import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
  static late Database _database;

  DatabaseHelper._privateConstructor();

  Future<Database> get database async {
    if (_database != null) return _database;  // HERE: "The operand can't be null, so the condition is always true. Remove the condition"
    _database = await _initDatabase();
    return _database;
  }

  Future<Database> _initDatabase() async {
    Database _db = await openDatabase('my_db.db');
    return _db;
  }

}

因为检查 _database 是否为 null 是多余的,因为您将其声明为

static late Database _database;

Database这里是不可空类型,所以不能为空。

澄清一下,这是警告而不是错误。


要重构您的代码,请将 _database 变量声明为可为 null

static Database? _database;

和你的 database getter 作为

Future<Database> get database async {
  final Database? instance = _database;
  if (instance != null) return instance;
  instance = await _initDatabase();
  _database = instance;
  return instance;
}

是因为你在定义_database的时候,特地定义了它是不可为空的:

static late Database _database;

如果它是一个可以为空的,你会添加“?”

static late Database? _database;