2

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 ...;
                  }
                });
          })
Umut Arpat
  • 454
  • 1
  • 6
  • 18
  • check `AsyncMemoizer` - the official docs say: *"A class for running an asynchronous function exactly once and caching its result."* – pskink Sep 14 '21 at 08:07
  • You also could just save the `Future` to a member variable. – jamesdlin Sep 14 '21 at 08:11
  • Try to put `id` Inside GetBuilder that you can specify `id:"someText"` and same text given in `update(["someText"])` will trigger the rebuilding. if `update()` without id its not going to rebuild. – Arul Sep 14 '21 at 08:14

1 Answers1

2

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.

croxx5f
  • 5,163
  • 2
  • 15
  • 36