0

I created DatasetDatabase to handle some database function calls as following:

class DatasetDatabase{
  final Future<Database> database;

  DatasetDatabase(this.database);

  Future loadDatasetTable() async{
    final Database db = await database;
    final List<Map<String, dynamic>> table = await db.query('datasets');
    print(table[0]['dataset']);
    var _datasetList = jsonDecode(table[0]['dataset']).map<Dataset>((e) => Dataset.fromJson(e)).toList();
    return _datasetList;
  }

At the same time I have DatabaseService class where I would like to get database and instantiate databases. However, I can't simply pass database as parameter as it can't be accessed in the initializer.

class DatabaseService{

  Future<Database> get database async {
    Database _database = await openDatabase(
      join(await getDatabasesPath(), 'caralgo_database.db'),
      onCreate: (db, version) {
        db.execute(
            "CREATE TABLE datasets(id INTEGER PRIMARY KEY, dataset TEXT)"
        );
        db.execute(
            "CREATE TABLE unitConfigs(id INTEGER PRIMARY KEY, unitConfig TEXT)"
        );
      },
      version: 1,
    );
    return _database;
  }

  final DatasetDatabase datasetDatabase = DatasetDatabase(database);
  final UnitConfigDatabase unitConfigDatabase = UnitConfigDatabase(database);
}

One of the solutions is to make get database static, but I would like to avoid it. Is there any other way to do it?

  • This seems like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What problem are you trying to solve? If you don't want `DatabaseService.database` to be `static`, then just omit the `static` keyword. Doing so would require clients to construct a `DatabaseService` instance first, however. – jamesdlin Feb 04 '22 at 12:43
  • Thank you for your comment I will provide more explanation. – Julian Modlinski Feb 04 '22 at 13:44
  • If I understand your problem correctly, your goal is to have a class that has data members initialized with the result of an instance method. If so, see https://stackoverflow.com/q/65601214/. – jamesdlin Feb 04 '22 at 20:51

0 Answers0