Getting values from Future instances

前端 未结 2 635
野性不改
野性不改 2021-01-05 04:05

My data is something like this:

{
  \"five\": {
    \"group\": {
      \"one\": {
        \"order\": 2
      },
      \"six\": {
        \"order\": 1
      }         


        
相关标签:
2条回答
  • 2021-01-05 04:21

    You are not waiting for the await value expressions to complete.

    The forEach call runs through the map entries and starts an asynchronous computation for each. The future of that computation is then dropped because forEach doesn't use the return value of its function. Then you return the map, far before any of the asynchronous computations have completed, so the values in the map are still futures. They will eventually change to non-futures, but you won't know when it's done.

    Instead of the forEach call, try:

    await Future.wait(groupMapWithDetails.keys.map((key) async {
      groupMapWithDetails[key] = await groupMapWithDetails[key];
    });
    

    This performs an asynchronous operation for each key in the map, and the waits for them all to complete. After that, the map should have non-future values.

    0 讨论(0)
  • 2021-01-05 04:44

    There is no way to get back from async execution to sync execution.

    To get a value from a Future there are two ways

    pass a callback to then(...)

    theFuture.then((val) {
      print(val);
    });
    

    or use async/await for nicer syntax

    Future foo() async {
      var val = await theFuture;
      print(val);
    }
    
    0 讨论(0)
提交回复
热议问题