I’ve a Map<int, Future<GpxCoordinates>>
in which the int
key is the id of the entity and the future contains the async call to my API to get data for the related entity id.
I need to start all the requests togethers and then await them.
That’s my not working implementation:
try {
Map<int, Future<GpxCoordinates>> gpxsCoordinatesToFetch = {};
for (var tourId in event.toursIds) {
gpxsCoordinatesToFetch[tourId] = gpxRepository.fetchGpxCoordinates(tourId);
}
// Problem in the return await type
final gpxsCoordinates = await Future.wait(gpxsCoordinatesToFetch.values);
emit(GpxsCoordinatesLoaded(coordinates: gpxsCoordinates));
} catch (e) {
debugPrint(e.toString());
emit(GpxError());
}
The problem is that the Future.await
returns a List<GpxCoordinates>
but I need to return a Map<int, GpxCoordinates>
. Does it exists a way to obtain the desired Map<int, GpxCoordinates>
once all requests have been finished?
2
Answers
You have to somehow connect the received data with the id. This is one of the ways to achieve it:
Outputs:
{1: some value, 2: some value}
Another one (probably better):
Replace
with