我在下面有一个类&方法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);
}