How to call a function to update a value after popping a screen in Flutter?

Viewed 12311

Screen 1: shows list of item with add button. Screen 2: form to add a new item to the list.

Screen 2 >> Screen 1 - While calling navigator.pop() in screen 2, how to call method/setState (to update list) in screen 1? Can anyone help me out?

I don't want to relaunch screen again. I just need to run a method to update my list after popping previous screen?

4 Answers

When you navigate from Screen 1 to Screen 2, you use the push method. The push method returns a Future object. You can use the then method of Future to execute your code after Screen 2 was popped from the navigation stack.

Navigator.of(context)
  .push(MaterialPageRoute(
     builder: (context) => Screen2(),
  ))
  .then((value) {
    // you can do what you need here
    // setState etc.
  });

You can use Provider or BLoc or you can await for the result when you push the page

Navigator.pop has a second argument called result. You could then return the value that you need to the first page that will read it as the return value of Navigator.push

You can do it like this :

// this method waits for the pop to be called
var data = await Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => LoginScreen()),
);

debugPrint(data); 

// here the second argument is the data 
Navigator.pop(context, "data");  // popped from LoginScreen().

output

data

Same method can also be done like below

   // this method waits for the pop to be called
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => LoginScreen()),
).then((data){
    // then will return value when the loginScreen's pop is called.
    debugPrint(data); 
});

Here is a good article to look into this https://medium.com/flutter-community/flutter-push-pop-push-1bb718b13c31

Related