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();
}
...
6
  • what _createDatabase() do in your code? Does it initialize the _database ? Commented Dec 14, 2021 at 18:38
  • Yes, it's opening database with await openDatabase() and returning Future<Database> Commented Dec 14, 2021 at 18:41
  • then, did you set the returned object to _database?, something like: _database = await openDatabase()? Commented Dec 14, 2021 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. Commented Dec 14, 2021 at 19:12
  • How about: Future<Database> get database async { if (_database == null) { _database = await _createDatabase(); } return _database; } ? Commented Dec 14, 2021 at 20:08

1 Answer 1

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!;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can late be used in some way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.