3

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();
}
...
Mayketi
  • 93
  • 11
  • what `_createDatabase()` do in your code? Does it initialize the `_database` ? – ישו אוהב אותך Dec 14 '21 at 18:38
  • Yes, it's opening database with `await openDatabase()` and returning `Future` – Mayketi Dec 14 '21 at 18:41
  • then, did you set the returned object to `_database`?, something like: `_database = await openDatabase()`? – ישו אוהב אותך Dec 14 '21 at 18:57
  • I didn't set returned object to `_database` because `_database` is assigned to `_createDatabase()` and that function is returning `Database` object. I tried to change getter method to `if (_database != null) return _database!` and `_database = await _createDatabase()`. But still same. Every time I try to insert to database I get new database instance with only one entry. – Mayketi Dec 14 '21 at 19:12
  • How about: `Future get database async { if (_database == null) { _database = await _createDatabase(); } return _database; }` ? – ישו אוהב אותך Dec 14 '21 at 20:08
  • I am getting and error: `A value of type 'Database?' can't be returned from the function 'database' because it has a return type of 'Future'` and a warning: `Prefer using ??= over testing for null.`. And if I change return type to `` I get an error in my provider as well: `The method 'insert' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').` – Mayketi Dec 14 '21 at 20:18

1 Answers1

1

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!;
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96