![](/img/trans.png)
[英]How to convert list getting from future method to Map<String, dynamic>
[英]How to save `Map<String, dynamic>` returning from async method in the constructor?
我有一个像下面这样的类 & 方法readJson
返回Future<Map<String, dynamic>>
并且在构造函数TestRemoteConfigManager(){}
中,我想将返回值分配给testValues
。!
我在非异步方法中调用异步方法时遇到问题。 有帮助吗?
class TestRemoteConfigManager {
Map<String, dynamic> testValues = {};
TestRemoteConfigManager() {
readJson().then((value) => testValues = value);
SLogger.i('testValues from contructor-->$testValues');
}
Future<Map<String, dynamic>> readJson() async {
final Map<String, dynamic> data = await json.decode(
await rootBundle.loadString('assets/uat/remote_config_defaults.json'));
SLogger.i('read data: $data');
return data;
}
}
如果您关心在构造函数中等待异步调用的结果,最好使用静态方法来完成异步工作,然后使用私有构造函数返回对象的实例。 像这样:
class TestRemoteConfigManager {
Map<String, dynamic> testValues;
static Future<TestRemoteConfigManager> create() async {
final values = await readJson();
return TestRemoteConfigManager._(values);
}
static Future<Map<String, dynamic>> readJson() async {
// ...
}
// Declaring this private constructor means that this type can only be
// instantiated through TestRemoteConfigManager.create()
TestRemoteConfigManager._(this.testValues);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.