FlutterFutureBuilderWidgets

Use Multiple Futures with in Single FutureBuilder Widget

Sometimes, a situation may arise where multiple API calls are necessary to construct a widget. This widget contains the data of multiple sources. To build this widget we need to fetch all the data concurrently. Flutter facilitates this by utilising the FutureBuilder widget along with the wait() method. It enables the seamless integration of multiple API calls to gather essential data simultaneously for constructing a widget. FutureBuilder allows to use multiple futures with in single widget.

How to wait for multiple Futures in Single Widget

Let’s see here an example:

import 'dart:convert';
import 'package:http/http.dart';

Future<dynamic> firstFuture() async {
    const String myEndpoint = "https://....";
    Response response = await Client().get(Uri.parse(myEndpoint));
    return jsonDecode(response.body)["data"];
}

Future<dynamic> secondFuture() async {
    const String myEndpoint = "https://....";
    Response response = await Client().get(Uri.parse(myEndpoint));
    return jsonDecode(response.body)["data"];
}

Theis code demonstrates the usage of two asynchronous methods making calls to distinct endpoints. Each enpoint is returning JSON data.

Now Let’s see how these methods can be employed within the build process of a MaterialApp.

FutureBuilder(
  future: Future.wait([firstFuture(), secondFuture()]),
  builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
    print(snapshot.hasData);
    if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {
      print("First future result: ${snapshot.data[0]}");
      print("Second future result: ${snapshot.data[1]}");
      return const MyWidget();
    } else {
      return CircularProgressIndicator();
    }
  },
),

The FutureBuilder widget contains a parameter named “future”. This parameter accepts a list of Future which is obtained through the Future.wait() method. This approach allows us to efficiently await the completion of multiple futures. After the completion of futures we access their respective results, and seamlessly render additional widgets based on the gathered data.

You can also see how to solve FutureBuilder Called multiple times problem

Leave a Reply

Your email address will not be published. Required fields are marked *