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");
}
}
有一个更好的方法吗?
解决方案
您可能希望您可以拥有异步工厂构造函数,但它们是不允许的。
所以一个解决方案是 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();
推荐阅读
- java - 从 JSP 中检索嵌套列表的值并将其发送回表单
- .net - FlowDocument 如何包含无格式文本(例如代码示例)
- python - Python:正则表达式,在字符串上查找重复
- azure - 生成不记名令牌时签名无效
- python - 获取python中嵌套最深的dict的值
- xmlunit-2 - XMLUnit NodeFilter 没有发现差异
- java - 在同一窗口中打开另一个 GridPane
- java - 有没有办法在eclipse中隐藏一个包?(也许是出于安全原因?)
- soapui - 如何在Property transfer中将TestCase自定义属性值设置为Xpath中的参数
- php - PHP CURL 如何过滤 json 结果?