You can't do that with forEach
.
But you can use Future.wait
and .map
like this
Future<void> deleteAll(List stuff) {
return Future.wait(stuff.map((s) => delete(s)));
}
Future<void> delete(Stuff s) async{
....
await file.writeAsString(jsonEncode(...));
}
When to use async
keyword:
You can use async
when your function uses await
keyword inside.
So when to use await
keyword:
- when you want to get the result from an asynchronous function and want do some logic on the result
Future<int> fetchCountAndValidate() asycn{
final result = await fetchCountFromServer();
if(result == null)
return 0;
else
return result;
}
- When you want to call multiple asynchronous function
Future<int> fetchTotalCount() asycn{
final result1 = await fetchCount1FromServer();
final result2 = await fetchCount2FromServer();
return result1 + result2;
}
When you don't need async
or await
:
- When you just calling another asynchronous function
Future<int> getCount(){
//some synchronous logic
final requestBody = {
"countFor": "..."
};
return fetchCountFromServer(requestBody); //this is an asynchronous function which returns `Future<int>`
}
- For some rare cases we doesn't care about the completion of asynchronous function
void sendLogoutSignal(){
http.post(url, {"username" : "id0001"});
}
Giovanni Terlingen
answer is correct. See these example Dartpad – Donnelldonnelly