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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With