Is there a callback when the FutureBuilder is done building in Flutter?

Viewed 1864

Is there a way to know when all the widgets are built in Flutter including FutureBuilder widgets. WidgetsBinding.instance.addPostFrameCallback is called when build is done, but before FutureBuilder is built.

I have a List inside a FutureBuilder whose data is fetched from the server. There is another Text widget outside FutureBuilder which shows the count of list items. I need to update this count widget when the list is populated .Without using a stream is there a callback method triggered when the FutureBuilder is built.

2 Answers

Just use WidgetsBinding.instance.addPostFrameCallback in your futurebuilder when has data and connection is done

FutureBuilder<List<Object>>(
    future: _listFuture,
    builder: (context, AsyncSnapshot snapshot) {
      
      if(snapshot.hasData && snapshot.connectionState == ConnectionState.done){
        WidgetsBinding.instance
            .addPostFrameCallback((_) {
              
        });
      }

      return ...
    }
);

There are many ways. If you intend to do this without using state management, you could use ValueNotifier.

ValueNotifier<int> total = ValueNotifier(0);

FutureBuilder()..future.then((snapshot) {
                  total.value = snapshot.total;
                });

ValueListenableBuilder(
            valueListenable: total,
            builder: (context, value, widget) {
              return Text(value.toString());
            },
          ),

Bu i suggest you use provider package

Related