This is not really more convenient than Navigator.push().then()
but you could use a RouteObserver
to detect the page changes.
Code
For this example I am going to define 2 global variables:
final routeObserver = RouteObserver<ModalRoute<void>>();
int count = 0; // Number of times you are entering the page
Then add routeObserver
to your MaterialApp.navigatorObservers
:
MaterialApp(
home: InitialPage(),
navigatorObservers: [routeObserver],
)
Finally, you will need to manage the subscription of your routeObserver
to your page. For this you will have to use a StatefulWidget
as your "enter on page" behavior will be defined thanks to the page's State
:
class InitialPage extends StatefulWidget {
@override
State<InitialPage> createState() => _InitialPageState();
}
class _InitialPageState extends State<InitialPage> with RouteAware {
@override
void initState() {
super.initState();
count++;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
routeObserver.subscribe(this, ModalRoute.of(context)!);
}
@override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}
@override
void didPopNext() {
super.didPopNext();
// view will appear
setState(() => count++);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('You entered on this page $count times'),
ElevatedButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => OtherPage(),
),
),
child: const Text('Press me'),
),
],
),
),
);
}
}
Basically what I am doing is incrementing the counter
when instanciating the page thanks to initState
(called when the page is added to the widget tree) and by registering the routeObserver
to your view I will be able to increment my counter when my page is already in the widget tree with didPopNext
(and using a setState
to update my UI).
You can try the full example on DartPad