databaseflutternull-safety

Even though I used late for filed in flutter, a null safety error is occurring


In my code, 'db' leads to null safety problem. Below is the code I wrote

class DbHelper{
  final int version = 1;
  late Database db;

  Future<Database> openDb() async {
    if (db == null){
      db = await openDatabase(join(await getDatabasesPath(), 'shopping.db'),
          onCreate: (database, version) {
            database.execute(
                'CREATE TABLE lists(id INTEGER PRIMARY KEY, name TEXT, priority INTEGER)');
            database.execute(
                'CREATE TABLE items(id INTEGER PRIMARY KEY, '+
                    'idList INTEGER, name TEXT, quantity TEXT, '+
                    'note TEXT, ' + 'FOREIGN KEY(idList) REFERENCES lists(id))');
          }, version: version);
    }
    return db;
  }
}

I tried deleting late or using ? in the field value db. but the problem is not solved.


Solution

  • As the comments under your question suggest, you should remove late and instead use a nullable type Database?. You can read more about the differences between these two abstractions here: https://dart.dev/null-safety/understanding-null-safety

    The whole code would simply be:

    class DbHelper{
      final int version = 1;
      Database? db;
    
      Future<Database> openDb() async {
        if (db == null){
          db = await openDatabase(join(await getDatabasesPath(), 'shopping.db'),
              onCreate: (database, version) {
                database.execute(
                    'CREATE TABLE lists(id INTEGER PRIMARY KEY, name TEXT, priority INTEGER)');
                database.execute(
                    'CREATE TABLE items(id INTEGER PRIMARY KEY, '+
                        'idList INTEGER, name TEXT, quantity TEXT, '+
                        'note TEXT, ' + 'FOREIGN KEY(idList) REFERENCES lists(id))');
              }, version: version);
        }
        return db!;
      }
    }