首页 > 解决方案 > 用异步变量初始化类

问题描述

如何使用异步变量初始化类,以便在使用类之前设置它们?我的班级目前只是调用一个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");
  }
}

有一个更好的方法吗?

标签: dart

解决方案


您可能希望您可以拥有异步工厂构造函数,但它们是不允许的

所以一个解决方案是 a 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();

推荐阅读