Search code examples
fluttersqlitedartsqflitedart-null-safety

How to set up sqlite database in flutter with null safety?


I've been struggling for a while to set up a sqlite database with sqflite in flutter. Code is producing a new instance of the database every time I call the getter method for a database. Here is the code:

class DatabaseProvider {
  DatabaseProvider._();
  static final DatabaseProvider dbProvider = DatabaseProvider._();

  static Database? _database;

  Future<Database> get database async => _database ??= await _createDatabase();
}
...

Solution

  • You need to initialize the _database in your getter. So, change it to this:

    Future<Database> get database async {
      if (_database == null) {
         // initialize database from _createDatabase result.
        _database = await _createDatabase();
      }
      // because _database have beeen initialized above, 
      // then we can use ! to tell that the _database can't be null.
      return _database!;
    }