Search code examples
fluttercallbacknavigator

How do I reset the Navigator.pop call back value in Flutter?


Please bear with my explanation below. I have a page with 2 BottomNavigationBar Items:

Page1(),
Page2(),

In Page1 there is a button which navigates to another page called PostSomethingPage:

// in Page1
onPressed: () => Navigator.push(
   context, MaterialPageRoute<bool>(builder: 
     (context) => PostSomethingPage()))
        .then((isPostSuccess) => isPostSuccess 
          ? print('is Success!') : print('Failed!'));

You can see that Page1 is expecting a return boolean value from PostSomethingPage and will print based on it.

Here is the code in PostSomethingPage that returns the result:

// in PostSomethingPage
Navigator.pop(context, isSuccess);

Then once we went back to Page1, the value from the call back has been received and the print statement was executed accordingly, everything seems fine at this point.

But then a problem arise when I navigate to Page2 and back to Page1
Note: at this point I have been from Page1 => PostSomethingPage => back to Page1 with the result, after that then go to Page2

Because when I went back again to Page1 the print statement will get printed again based on the LAST known value. But what I want is to reset the call back value to be empty instead of having true or false


Solution

  • use a variable to store the value return by PostSomethingPage

    //our variable initialized with null
    bool isPostSuccess;
    
    @override
    Widget build(BuildContext context) {
      return FlatButton(onPressed: () async {
        //going to PostSomethingPage from Page1
        isPostSuccess = await Navigator.of(context).push(
            MaterialPageRoute<bool>(builder: (context) {
              return PostSomethingPage();
            })
        );
      }, child: Text(''));
      //we are back at the Page1
      //isPostSuccess will not be null
    }
    

    now before you go to Page2 simply set the value of isPostSuccess to null again

        //going to Page2 from Page1
        isPostSuccess = null;
        Navigator.of(context).push(
            MaterialPageRoute<bool>(builder: (context) {
              return Page2();
            })
        );