0

I am very new to dart and follow a tutorial which was created in an earlier version of dart i think. However, the _database variable throws the error

Non-nullable instance field '_database' must be initialized.

I am not sure but i think its because the type safety thing, therefore, the getter which will act as a "singleton mechanism" won't work and the _database must be initialized before. How can i create the database connection when its requested by the getter?

Thanks

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

  Database _database;

  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await createDatabase();
    return _database;
  }

  createDatabase() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, "test.db");
    Database database = await openDatabase(path);
    return database;
  }
}

PS: my IDE suggest to use the late keyword, which i read is a bad thing and should be avoided in that case, since we have also to check if its already inititialized - a feature dart does not provide(?)

Jim Panse
  • 2,220
  • 12
  • 34
  • 1
    `_database` should be declared as nullable (`Database? _database`) since your code assumes that it can be `null`. – jamesdlin Mar 23 '23 at 23:43
  • but if i do so, the Future return value is not applicable anymore ... should it then be Future ? Feels a bit weird actually – Jim Panse Mar 24 '23 at 11:16

1 Answers1

2

You can use the singleton pattern to create an instance of DatabaseProvider:

class DatabaseProvider {
  static DatabaseProvider? _instance;
  static Database? _database;

  factory DatabaseProvider() => _instance ??= DatabaseProvider._();

  DatabaseProvider._();

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

  Future<Database> createDatabase() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, "test.db");
    Database database = await openDatabase(path);

    return database;
  }
}

Singleton Pattern in Dart: https://stackoverflow.com/a/59026238/9455518

Hamed
  • 5,867
  • 4
  • 32
  • 56