Search code examples
flutterdartfutureflutter-futurebuilderflutter-future

How can I update the data fetched from a future bilder in Flutter?


In my app I have a screen which contains 3 different future builders, I would like to update the data recovered from a future builder. I tried the setState () method but this updates all 3 future builders on the page, I only need to update one. How can I do ?

My 3 future builders are structured like this:

FutureBuilder(
future: getData(), //Fetch the data
builder:
    (context, AsyncSnapshot snapshot) {
  if (snapshot.connectionState == ConnectionState.done) {
    return Text('${snapshot.data}',
        style: const TextStyle(
            fontSize: 15,
            color: Colors.black));
  } else {
    return const CircularProgressIndicator.adaptive();
  }
})

Solution

  • If you want to rebuild just a portion of your screen, you can use StatefulBuilder. Wrap the single FutureBuilder you want to rebuild with a StatefulBuilder like so:

    StatefulBuilder(
     builder: (context, setState) {
      return YourFutureBuilder();
     },
    )
    

    If setState is called from inside the StatefulBuilder, only the portion of the screen that is wrapped with the StatefulBuilder will be rebuilt.