【问题标题】:Using a variable that requires async in every method of a class在类的每个方法中使用需要异步的变量
【发布时间】:2020-04-22 18:53:18
【问题描述】:

我正在尝试创建一个简单的类,使用this package 处理非常简单的数据库操作。

在课堂上,我创建了一个变量(一个名为 db 的数据库)。我想将变量放在类的根目录中,以便我的所有方法都可以访问该变量。但要初始化该变量,我必须使用异步函数。

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"});
  }
}

因此,我无法在 addGroup 方法中访问变量 db。如何使需要异步函数的变量可供我的整个班级使用?

我还尝试返回变量 db 并将其分配给我的类根目录下的变量,但这会产生错误,在初始化程序中只能访问静态成员。

  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;
  }

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以在构造函数中调用 setter 函数

    
    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"});
      }
    }
    
    

    现在它将可用于该类的实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 2013-12-15
      • 2017-02-10
      • 2019-03-19
      • 2014-08-26
      • 1970-01-01
      • 2021-02-13
      相关资源
      最近更新 更多