Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Combine Multiple Future<T> Tasks

How we can merge multiple FutureTask so that we can get a callback for all at the same response.

We use Future<T> like

Future<String> getData(int duration) async {
  await Future.delayed(Duration(seconds: duration)); //Mock delay
  return "This a test data for duration $duration";
}

Call above method like getData(2).then((value) => print(value));

If we want to call multiple Future Task, then how can we do that?

like image 648
Jitesh Mohite Avatar asked Dec 31 '22 23:12

Jitesh Mohite


1 Answers

To execute all futures concurrently, use Future.wait This takes a list of futures and returns a future of lists: Suppose you have these futures.

class CovidAPI {
  Future<int> getCases() => Future.value(1000);
  Future<int> getRecovered() => Future.value(100);
  Future<int> getDeaths() => Future.value(10);
}

You can get all the futures together using Future.wait([list of futures])

final api = CovidAPI();
final values = await Future.wait([
    api.getCases(),
    api.getRecovered(),
    api.getDeaths(),
]);
print(values); // [1000, 100, 10]

This is ideal when the futures are independent, and they don't need to execute sequentially. Source : https://codewithandrea.com/videos/top-dart-tips-and-tricks-for-flutter-devs/

like image 81
Sourav9063 Avatar answered Feb 05 '23 03:02

Sourav9063