Warm tip: This article is reproduced from stackoverflow.com, please click
android asynchronous flutter future

Dart: How to return Future

发布于 2020-03-27 15:47:34

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?

Questioner
Pascal
Viewed
88
Giovanni 2020-02-01 23:38

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.