Search code examples
flutterflutter-navigation

How to simulate device back btn press/ AppBar back press? WillPopScope is not called upon Navigator.pop()


I was able to override the back button onPressed behavior using WillPopScope. Now, whenever I press the device back button or the default AppBar back button, the code inside onWillPop runs as expected.

The problem now is that I want to have my own custom buttons to navigate backward, but Navigator.of(context).pop() doesn't check the WillPopScope as if it doesn't exist.

  • Is there a way to simulate the system's back behavior or call it somehow?
  • I know I can just call the same function that is called by onWillPop() manually upon pressing my custom back button, but I was eager to find a cleaner method, as in the future I could easily forget doing that and cause bugs.

Solution

  • The key was to use Navigator.of(context).maybePop()instead. Or more specifically in my case, was to use Navigator.of(context, rootNavigator:true).maybePop() as I was using nested Navigation.