Greg
Greg

Reputation: 34818

why does this Dart code give "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"?

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;
  }

}

enter image description here

Upvotes: 0

Views: 304

Answers (2)

Canada2000
Canada2000

Reputation: 1708

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;

Upvotes: 2

enzo
enzo

Reputation: 11496

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;
}

Upvotes: 1

Related Questions