简体   繁体   中英

How to save `Map<String, dynamic>` returning from async method in the constructor?

I have a class like below & method readJson which returns Future<Map<String, dynamic>> and in constructor TestRemoteConfigManager(){} , I want to assign the returned value to testValues .!

I'm getting issues as calling async method in non async method. Any helps?

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;
  }
}

If you care about waiting for the results of asynchronous calls in a constructor, you're better off using a static method to do the asynchronous work that then returns an instance of your object using a private constructor. Something like this:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM