How to cache Future in FutureBuilder's Future.wait function to not rebuild everytime state changes

Issue

I want to use multiple Futures so I implemented Future.wait functionality in FutureBuilder.

But it keeps rebuilding whenever page state changes. How can I cache futures in Future.wait ?

Here is the code:

GetBuilder<OrdersMainController>(builder: (controller) {
            return FutureBuilder(
                future: Future.wait([controller.ordersFuture.value]),// lets me use multiple futures
                builder: (context, snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.active:
                    case ConnectionState.waiting:
                    case ConnectionState.done:
                      if (snapshot.hasError) {
                        return SizedBox(
                            width: double.infinity,
                            height: 600,
                            child: Center(
                                child: Text(snapshot.error.toString(),
                                    style:
                                        Theme.of(context).textTheme.caption!)));
                      }
                      controller.ordersData.value = (snapshot.data! as List)[0];
                      final DataTableSource _data =
                          OrdersMainSource(controller.ordersData.value.data!);
                      return ...
                    default:
                      return ...;
                  }
                });
          })

Solution

Instead of calling your Future.wait() on every build use a StatefulWidget and cache the computation inside its state(Note that the state object survives rebuilds).

class _MyWidgetState extends State<MyWidget> {
late final lotsOfData=Future.wait([controller.ordersFuture.value])
 @override
  Widget build(BuildContext context) {
.....
 return FutureBuilder(
                future: lotsOfData,


By declaringlotsOfData as a late final variable inside the State object you are actually caching it. And by declaring it late you don’t start the Futures eagerly but on first access.

Answered By – croxx5f

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

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