How to get notified for a parallel futures in flutter

Issue

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]

Solution

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;
}

Answered By – Nagual

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.