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.
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.