2

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;
}
1
  • Enabling the await_only_futures lint would have given you a hint about your problem. Commented Feb 16, 2022 at 21:29

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Nitpick: Iterable.map always returns an Iterable (which also is lazily evaluated). (Using Future.wait will still fix the problem, though.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.