Home > Software design >  Flutter Does FutureBuilder reload data after changing page?
Flutter Does FutureBuilder reload data after changing page?

Time:06-27

Use case:

  1. FutureBuilder loads data and builds widget*
  2. I press a button → I change page/screen
  3. I go back to the futureBuilder's screen by pressing a button

Question: Does the futureBuilder reload data ?

CodePudding user response:

I assume you're pushing another route onto the Navigator and then popping it off again? In that case, the underlying screen will not rebuild.

You could await the result of the second screen and then reload the data again.

// where the second screen is initiated

await Navigator.of(context).push(routeToSecondScreen);
setState(() {});

// in its build method

FutureBuilder(
  future: getData(),
  builder: (context, snapshot) {
    //...
  },
), 

This will execute a rebuild of the first screen after the second is popped. The rebuild will recreate the FutureBuilder and execute the getData() function.

However, if the Future is part of your screen's state, you might want to execute myFuture = getData(); within the setState function.

late Future myFuture;

void initState() {
  myFuture = getData();
  super.initState();
}

// where the second screen is initiated

await Navigator.of(context).push(routeToSecondScreen);
setState(() {
  myFuture = getData();
});

// in its build method

FutureBuilder(
  future: myFuture,
  builder: (context, snapshot) {
    //...
  },
), 

CodePudding user response:

by just adding a setstate call back will reload the page after pop

replace the button press in FutureBuilder class to navigate to other class with the following,

Navigator.push(context, MaterialPageRoute(builder:
        (context)=>SecoundScreen())).then((value) {
      setState(() {
        
      });
    });

CodePudding user response:

It depends

If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

See the official docs


In other word if you create the Future directly inside the future param,

  FutureBuilder(
     future: Future.delayed(...), 
     builder: ...
  );

then the task is executed on every parent re-render (cause you are actually creating a new Future every time the build method is executed).

You need to create your Future before (like initState function), and storing it in some prop, than pass it to the FutureBuilder.

Something like

late Future _myFuture;

initState() {
   _myFuture = Future.delayed(...);
   super.initState();
}

build(context) {
  return FutureBuilder(
     future: _myFuture, 
     builder: ...
  )
}

so that in every render, the promise will be the same (and eventually already resolved in future renders)

  • Related