You can use the onGenerateRoute property on the MaterialApp to listen and execute your methods each time a named route is made ( when you navigate over pages in your pages) :
MaterialApp(
onGenerateRoute: (settings) {
print("navigated to new route")
},
//...
You can use WillPopScope widget to listen for the navigator’s pop() method which goes back to the previous screen if it exists in the stack route, and close the app when it’s the only one left in the stack route.
WillPopScope(
onWillPop: () async {
print("route popped");
return Future.value(true);
}, child: WillPopScope(
onWillPop: () async {
print("route popped");
return Future.value(true); // will allow popping, if the value is false, it will not pop.
},
child: Scaffold(//...)
if you’re willing to use a custom personalized Navigator in your app, then you can set from it the onGeneratedRoute and also the onPopPage which let you listen to pop() over the sub-tree it takes:
Another option you can do, is to use life cycle methods to execute a piece of code whenever a widget screen is rendered ( initState() will run), and when you pop() it, it will be disposed ( dispose() will execute ), but it requires using StatefulWidget:
3
Answers
You can use the
onGenerateRoute
property on theMaterialApp
to listen and execute your methods each time a named route is made ( when you navigate over pages in your pages) :You can use
WillPopScope
widget to listen for the navigator’spop()
method which goes back to the previous screen if it exists in the stack route, and close the app when it’s the only one left in the stack route.if you’re willing to use a custom personalized
Navigator
in your app, then you can set from it theonGeneratedRoute
and also theonPopPage
which let you listen topop()
over the sub-tree it takes:Another option you can do, is to use life cycle methods to execute a piece of code whenever a widget screen is rendered (
initState()
will run), and when youpop()
it, it will be disposed (dispose()
will execute ), but it requires usingStatefulWidget
:1- when switch to another app as well as return to the app You can use
WidgetsBindingObserver in your widgets and listen to AppLifecycleState.
2- in order to handle resume callback
3- to perform some function on app close try to use willpopscope