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);
Author by
Mirza Celik
Updated on December 19, 2022Comments
-
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 about 2 yearsEnabling the
await_only_futures
lint would have given you a hint about your problem.
-
-
jamesdlin about 2 yearsNitpick:
Iterable.map
always returns anIterable
(which also is lazily evaluated). (UsingFuture.wait
will still fix the problem, though.)