How can I return Future<void>
?
Future<void> deleteAll(List stuff){
stuff.forEach( s => delete(s)); //How do I return Future<void> when loop and all delete Operation are finished?
}
Future<void> delete(Stuff s) async {
....
file.writeAsString(jsonEncode(...));
}
How do I return Future<void>
when the forEach
loop and all delete Operations are finished?
You don't need to return anything manually, since an async
function will only return when the function is actually done.
Looking at your examples you are missing the async
keyword, which means you need to write the following instead:
Future<void> deleteAll(List stuff) async {
stuff.forEach( s => delete(s));
}
Future<void> delete(Stuff s) async {
....
await file.writeAsString(jsonEncode(...));
}
There is no need to return anything, since void
is nothing, as the name implies.
Also make sure you call deleteAll
and writeAsString()
using await
.
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:
Future<int> fetchCountAndValidate() asycn{
final result = await fetchCountFromServer();
if(result == null)
return 0;
else
return result;
}
Future<int> fetchTotalCount() asycn{
final result1 = await fetchCount1FromServer();
final result2 = await fetchCount2FromServer();
return result1 + result2;
}
When you don't need async
or await
:
Future<int> getCount(){
//some synchronous logic
final requestBody = {
"countFor": "..."
};
return fetchCountFromServer(requestBody); //this is an asynchronous function which returns `Future<int>`
}
void sendLogoutSignal(){
http.post(url, {"username" : "id0001"});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.