使用异步变量初始化类

时间:2018-05-20 19:54:06

标签: dart

如何使用异步变量初始化类,以便在使用类之前设置它们?我的班级目前只调用async init函数,但我必须单独调用它以等待它完成:

class Storage {

  String imageDirectory;
  String jsonDirectory;
  SharedPreferences instance;
  String uuid;

  init() async {
    imageDirectory = '${(await getApplicationDocumentsDirectory()).path}/image_cache/';
    jsonDirectory = '${(await getApplicationDocumentsDirectory()).path}/json_cache/';
    instance = await SharedPreferences.getInstance();
    uuid = instance.getString("UUID");
  }
}

有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

您可能希望您可以拥有异步工厂构造函数,但它们aren't allowed

因此,一个解决方案是static getInstance(),例如:

class Storage {
  static Future<Storage> getInstance() async {
    String docsFolder = (await getApplicationDocumentsDirectory()).path;
    return new Storage(
        docsFolder + '/image_cache/',
        docsFolder + '/json_cache/',
        (await SharedPreferences.getInstance()).getString('UUID'));
  }

  String imageDirectory;
  String jsonDirectory;
  String uuid;

  Storage(this.imageDirectory, this.jsonDirectory, this.uuid);
}

您可以根据需要将参数传递到getInstance,然后传递到构造函数中。请拨打以上电话:

Storage s = await Storage.getInstance();