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 {
  static final DatabaseProvider dbProvider = DatabaseProvider._();

  static Database? _database;

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


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

Answered By – ישו אוהב אותך

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *