skip to Main Content

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


  1. You have to somehow connect the received data with the id. This is one of the ways to achieve it:

    try {
      final Map<int, String> values = {};
      final List<Future> futures = [];
      for (var tourId in [1, 2]) {
        futures.add(Future.microtask(() async {
          // Do the call here
          final String value = await Future.value('some value');
    
          values[tourId] = value;
        }));
      }
    
      await Future.wait(futures);
    
      print(values);
    } catch (e) {
      // ...
    }
    

    Outputs:
    {1: some value, 2: some value}

    Another one (probably better):

    ...
    for (var tourId in [1, 2]) {
      futures.add(
        Future.value('some value').then((value) => values[tourId] = value),
      );
    }
    ...
    
    Login or Signup to reply.
  2. Replace

      // Problem in the return await type
      final gpxsCoordinates = await Future.wait(gpxsCoordinatesToFetch.values);
    

    with

    Map<int,GpxCoordinates> gpxsCoordinates = {};
    for (final mapEntry in gpxsCoordinatesToFetch.entries) {
       final key = mapEntry.key;
       final futureVal = mapEntry.value;
       gpxsCoordinates[key] = await futureVal;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search