Flutter: I still get the error "Null check operator used on a null value" on the value I made Nullable

Viewed 30
 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);
      }

I get the error Null check operator used on a null value even though I made the _db value nullable.

Appreciate if someone can advise. Thank you in advance!

3 Answers

Nullable simply means that a variable can have a nullvalue. With the ! you assume that the variable is not null at this point and therefore you can call the method. But of course if you don't have a value assigned in your object now, then it will try to call the method on null value.

Initialize somewhere in the code your database object before you try to make a query.

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

You have to initialize a null value before using the notation (!) on it else you're casting a null object as non-null. To avoid any errors, rewrite it as

return (await _db?.query(_tableName)) ?? [];

this will fail but no nullpointer exception will be thrown

You can return empty list or fetch again on null case, use ! only when you are certain the value is not null. It would be better to do a null check 1st.

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