Why does this Dart code give "The operand can't be null, so the condition is always true. Remove the condition"?
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;
}
}
CodePudding user response:
Because checking if _database
is null is redundant, since you're declaring it as
static late Database _database;
Database
here is an non-nullable type, therefore it can't be null.
Just to make it clear, this is a warning rather than an error.
To refactor your code, declare the _database
variable as nullable
static Database? _database;
and your database
getter as
Future<Database> get database async {
final Database? instance = _database;
if (instance != null) return instance;
instance = await _initDatabase();
_database = instance;
return instance;
}
CodePudding user response:
It is because when you define _database
, you specifically defined it as non-nulable:
static late Database _database;
If it was a nullable one, you would add the "?"
static late Database? _database;