Wilson Wilson
Wilson Wilson

Reputation: 3737

Using a variable that requires async in every method of a class

I'm trying to create a simple class that handles really simple database operations using this package.

In the class, I create a variable (a database called db). I want to place the variable in the root of the class so that all my methods can access the variable. But to initialize that variable, I have to use an asynchronous function.

class Database {
  ObjectDB db;

  void openDatabase() async {
    Directory appDocDir = await getApplicationDocumentsDirectory();

    String dbFilePath = [appDocDir.path, 'user.db'].join('/');
    // initialize and open database
    db = ObjectDB(dbFilePath);
    db.open();
  }

  void addGroup(Group group) async {
    db.insert({"example": "Data"});
  }
}

Because of that, I can't access the variable db in the addGroup method. How can I make a variable that requires an asynchronous function, available to my entire class?

I also tried returning the variable db and assigning it to a variable at the root of my class, but that gives the error, only static members can be accessed in initializers.

  ObjectDB db = openDatabase();
  openDatabase() async {
    Directory appDocDir = await getApplicationDocumentsDirectory();

    String dbFilePath = [appDocDir.path, 'user.db'].join('/');
    // initialize and open database
    db = ObjectDB(dbFilePath);
    return db;
  }

Upvotes: 0

Views: 99

Answers (1)

Ahmed Khattab
Ahmed Khattab

Reputation: 2799

you can call a setter function inside your constructor


class Database {
  ObjectDB db;

   Database(){
      this.openDatabase();
   }

  void openDatabase() async {
    Directory appDocDir = await getApplicationDocumentsDirectory();

    String dbFilePath = [appDocDir.path, 'user.db'].join('/');
    // initialize and open database
    db = ObjectDB(dbFilePath);
    db.open();
  }

  void addGroup(Group group) async {
    db.insert({"example": "Data"});
  }
}

now it will be available to the instance of that class.

Upvotes: 1

Related Questions