Dart Future.wait for multiple futures and get back results of different types
You need to adapt each of your Future<T>
s to a common type of Future
. You could use Future<void>
:
List<Foo> foos;List<Bar> bars;List<FooBars> foobars;await Future.wait<void>([ downloader.getFoos().then((result) => foos = result), downloader.getBars().then((result) => bars = result), downloader.getFooBars().then((result) => foobars = result),]);processData(foos, bars, foobars);
Or if you prefer await
to .then()
, the Future.wait
call could be:
await Future.wait<void>([ (() async => foos = await downloader.getFoos())(), (() async => bars = await downloader.getBars())(), (() async => foobars = await downloader.getFooBars())(),]);
I think is not possible to do in a super nice fashion. All you can do is something like this:
void main() async { List<List<dynamic>> result = await Future.wait<List<dynamic>>([ getStringData(), getIntData(), ]); print(result[0]); print(result[1]);}Future<List<String>> getStringData() { return Future.value(["a", "b"]);}Future<List<int>> getIntData() { return Future.value([1, 2]);}
Well, type T is a generic type
You know your types, so you can work with them.
If your are using a FutureBuilder
, you can access the different results using this. (same order you put them in the Future.wait
method)
snapshot.data[0] // maybe type List<Foo>snapshot.data[1] // maybe type List<Bar>snapshot.data[2] // maybe type String