Dart Future.wait() for multiple futures

CodeWithFlutter
1 Min Read

Future.wait() is a method in Dart’s async package that allows you to wait for multiple Future objects to complete. It takes a list of Future objects as an argument and returns a new Future that completes when all the input Future objects complete.

Here’s an example of using Future.wait() to wait for multiple Future objects to complete:

import 'dart:async';

Future<void> fetchData() async {
  List<Future> futures = [
    fetchFromAPI1(),
    fetchFromAPI2(),
    fetchFromAPI3(),
  ];

  await Future.wait(futures);
}

Future<void> fetchFromAPI1() async {
  // Make API call and process the response
}

Future<void> fetchFromAPI2() async {
  // Make API call and process the response
}

Future<void> fetchFromAPI3() async {
  // Make API call and process the response
}

In this example, fetchData makes multiple API calls and waits for all the responses to come back. Once all the responses are received, fetchData continues executing its code.

Share this Article
Leave a comment