How to go back and refresh the previous page in Flutter?
You can trigger the API call when you navigate back to the first page like this pseudo-code
class PageOne extends StatefulWidget { @override _PageOneState createState() => new _PageOneState();}class _PageOneState extends State<PageOne> { _getRequests()async{ } @override Widget build(BuildContext context) { return new Scaffold( body: new Center( child: new RaisedButton(onPressed: ()=> Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new PageTwo()),) .then((val)=>val?_getRequests():null), ), )); }}class PageTwo extends StatelessWidget { @override Widget build(BuildContext context) { //somewhere Navigator.pop(context,true); }}
Or you can just use a stream if the API is frequently updated, the new data will be automatically updated inside your ListView
For example with firebase we can do this
stream: FirebaseDatabase.instance.reference().child( "profiles").onValue
And anytime you change something in the database (from edit profile page for example), it will reflect on your profile page. In this case, this is only possible because I am using onValue
which will keep listening for any changes and do the update on your behalf.
(In your 1st page): Use this code to navigate to the 2nd page.
Navigator.pushNamed(context, '/page2').then((_) { // This block runs when you have returned back to the 1st Page from 2nd. setState(() { // Call setState to refresh the page. });});
(In your 2nd page): Use this code to return back to the 1st page.
Navigator.pop(context);
For a more fine-grained, page-agnostic solution I came up with this Android Single LiveEvent mimicked behaviour.
I create such field inside Provider
class, like:
SingleLiveEvent<int> currentYearConsumable = SingleLiveEvent<int>();
It has a public setter to set value. Public consume
lets you read value only once if present (request UI refresh). Call consume
where you need (like in build
method).
You don't need Provider
for it, you can use another solution to pass it.
Implementation:
/// Useful for page to page communication/// Mimics Android SingleLiveEvent behaviour/// https://stackoverflow.com/questions/51781176/is-singleliveevent-actually-part-of-the-android-architecture-components-libraryclass SingleLiveEvent<T> { late T _value; bool _consumed = true; set(T val) { _value = val; _consumed = false; } T? consume() { if (_consumed) { return null; } else { _consumed = true; return _value; } }}