1

I know how Future.wait works

await Future.wait([
      functionA(),
      functionB()
    ]).then((data) {
     
    });

but what I want to know is

What if the number of functions is not fixed and the number of functions to be called varies depending on the situation? (the functions are all the same.)

dontknowhy
  • 2,480
  • 2
  • 23
  • 67

2 Answers2

3

Elaborating on my comments, you can dynamically build a List of Futures and use Future.wait on that. For example:

Future<void> doAsynchronousStuff() async {
  var waitList = <Future<void>>[];
  if (someCondition) {
    waitList.add(someAsynchronousFunction(someArgument));
  }

  if (someOtherCondition) {
    waitList.add(someOtherAsynchronousFunction(someOtherArgument));
  }

  // ... and so on...

  await Future.wait(waitList);
}

If you need to handle different return values from your asynchronous functions, you can use anonymous functions that set local variables. See Dart Future.wait for multiple futures and get back results of different types.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
1

As long as you have an iterable reference, you can map that and return the Future function.

Future<void> main() async {
  final List<int> resultFromApi = <int>[1, 2, 3, 4, 5];
  final List<int> finalResult = await Future.wait(resultFromApi.map(
    (int data) => complexProcess(data), // return the Future
  ));
  
  print(finalResult);
}

Future<int> complexProcess(int data) async {
  await Future<void>.delayed(const Duration(seconds: 1));
  return data * 10;
}
rickimaru
  • 2,275
  • 9
  • 13