Dart async await with a future

577

Since map always returns a List, not a Future, await has no effect, and the function simply immediately returns a List<Future>, and none of the individual Futures are awaited.

In order to await all of the futures, you can use Future.wait:

final formFieldFutures = tempFormFields.map((fieldData) async {
    // ...
});

final returnFormFields = await Future.wait(formFieldFutures);

print("#############  returnFormFields------");
print(returnFormFields);
print(returnFormFields.runtimeType);
Share:
577
Mirza Celik
Author by

Mirza Celik

Updated on December 19, 2022

Comments

  • Mirza Celik
    Mirza Celik over 1 year

    I have a situation where a map method is not completing before a return statement in a future list.

    Here is the code below. The line that prints "####### returnFormFields----" prints first and then the map runs. How can I make sure the map is done before returning me the data. Any help is greatly appreciated!

     void callFetchForms() async {
    
      var tempFormFields = [1, 2, 3, 4, 5];
    
      var tempFormFields2;
    
      tempFormFields2 = await get_select_system_field_data(tempFormFields);
    
      print("-----After response : tempFormFields2-------");
      print(tempFormFields2);
    }
    
    Future<List<dynamic>> get_select_system_field_data(tempFormFields) async {
    
    var returnFormFields = await tempFormFields.map((fieldData) async {
      print(fieldData);
      
       final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/users/${fieldData}'));
    
      if (response.statusCode == 200) {
        var returnData = await jsonDecode(response.body);
        print("Return data for ${fieldData}");
        print(returnData);
      } else {
        printWarning("Error in Response");
      }      
    
      return fieldData;
    }).toList();
    
    print("#############  returnFormFields------");
    print(returnFormFields);
    print(returnFormFields.runtimeType);
    
    return returnFormFields;
    }
    
    • jamesdlin
      jamesdlin about 2 years
      Enabling the await_only_futures lint would have given you a hint about your problem.
  • jamesdlin
    jamesdlin about 2 years
    Nitpick: Iterable.map always returns an Iterable (which also is lazily evaluated). (Using Future.wait will still fix the problem, though.)