0

Hello I am doing parallel network calls in flutter using the following code.

List<dynamic> results = await Future.wait([
      apiCall1(),
      apiCall2(),
      ...more api calls
 ]);
    

I need to update the status of each api call. Is there a way to know which api call was successfully completed and update something the status.

If I used .then in individual futures, the results list contains null.

void main() async {
  Future<int> future1 = Future.delayed(Duration(seconds: 1)).then((value) => 1);

  Future<int> future2 = Future.delayed(Duration(seconds: 2)).then((value) => 2);

  List<dynamic> results = await Future.wait([
    future1.then((value) {
      print(value);
    }),
    future2.then((value) {
      print(value);
    })
  ]);

  print(results);
}

1
2
[null, null]
raphire
  • 198
  • 9
  • take a look at here : https://stackoverflow.com/questions/54465359/future-wait-for-multiple-futures – Benyamin Aug 13 '21 at 15:03

1 Answers1

1

I think the simplest way is:

void main() async {
  Future<int> future1 = apiCall1();

  Future<int> future2 = apiCall2();

  List<int> results = await Future.wait([
    future1.then((value) {
      print(value);
      return value;
    }),
    future2.then((value) {
      print(value);
      return value;
    })
  ]);

  print(results);
}

Future<int> apiCall1() async {
  await Future.delayed(Duration(seconds: 1));
  return 1;
}

Future<int> apiCall2() async {
  await Future.delayed(Duration(seconds: 2));
  return 2;
}
Nagual
  • 1,576
  • 10
  • 17
  • 27
  • I already tried that. It is not working the `results` list does not contains value then as mentioned in the example code above. – raphire Aug 15 '21 at 08:47