I’m fetching data from APIs in Flutter. The data come from a several APIs, so I’m using Future.wait to make it smoother. I’ve got this variable:
late List<Cast> castMembers;
and this function:
Future<List<Cast>> getCast() async {
List<Cast> members= [];
// here is the logic of serialization etc...
return members;
}
and finally a function with Future.wait:
Future<void> callApi() async{
await Future.wait([
getAdresses(),
getCountries(),
getPrices(),
castMembers=await getCast()
]);
}
In this way Im getting an error. If I put the castMembers=await getCast()
before the Future.wait
it works fine, but in this case the methods inside the Future.wait
won’t excecute while we are waitng for the getCast()
.
Do you have any suggestion for this?
2
Answers
The should not have the field
castMembers
as a member in the array, because it is not aFuture
.When you type
castMembers=await getCast()
, this evaluatesgetCast()
, puts its value incastMembers
, and adds this value to the list.In other words, you should have:
instead of
If you want the initialize the variable, then do it separately:
Using
await
on aFuture<List<Cast>>
will produce aList<Cast>
. Therefore doingawait Future.wait([await getCast()]);
will try to callFuture.wait
with a non-Future
, and that isn’t allowed.As @pskink mentioned,
Future.wait
returns aList
of the returned values, which you could use:Presumably
getAdresses
(sic),getCountries
,getPrices
, andgetCast
all return different types, soresults
will be the nearest common base type (probablyObject
orList<Object>
), and you will need an explicit downcast. That’s a bit ugly, and it’s also slightly brittle since if you ever add newFuture
s toFuture.wait
call, you might need to adjust which element to access fromresults
, and that would not be enforced at compile-time.Alternatively, you can use the approaches that I described in Dart Future.wait for multiple futures and get back results of different types:
which is one of the few cases where I’d use
Future.then
. Or wrap the assignment in a separate function to use pureasync
–await
: