I have an easy solution if by “leaving the page” you mean that the user goes “back” from this page. The following solution will not work if you also want to get notified if the user opens up another page in front of the current one.
For the first case, you could use a WillPopScope.
It’s a class that notifies you when the enclosing ModalRoute
(internally used by the Navigator
) is about to be popped. It even leaves you a choice to whether or not you want the pop to happen.
Just wrap the second screen’s Scaffold
in a WillPopScope
.
return WillPopScope(
onWillPop: () async {
// You can do some work here.
// Returning true allows the pop to happen, returning false prevents it.
return true;
},
child: ... // Your Scaffold goes here.
);