In Flutter, is there any way to listen for navigation changes?
Example: Navigation is triggered in Widget A
:
Navigator.of(context).pushNamed('/chat');
When the above code is executed, I want an event to fire in a child of Widget A
. Is this possible?
Use RouteObserver:
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
then add this to root materialApp widget:
MaterialApp(
theme: ThemeData(),
navigatorObservers: [routeObserver],
)
we need to implement RouteAware in every widget that might be push or pop into the routes stack.
class Screen extends State<Screen3> with RouteAware{
...
@override
void didChangeDependencies() {
super.didChangeDependencies();
routeObserver.subscribe(this, ModalRoute.of(context));
}
@override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}
@override
void didPush() {
final route = ModalRoute.of(context).settings.name;
print('didPush route: $route');
}
@override
void didPopNext() {
final route = ModalRoute.of(context).settings.name;
print('didPopNext route: $route');
}
@override
void didPushNext() {
final route = ModalRoute.of(context).settings.name;
print('didPushNext route: $route');
}
@override
void didPop() {
final route = ModalRoute.of(context).settings.name;
print('didPop route: $route');
}
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.