Flutter - How the NavigatorObserver class works?
// Register the RouteObserver as a navigation observer.
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
void main() {
runApp(MaterialApp(
home: Container(),
navigatorObservers: [routeObserver],
));
}
class RouteAwareWidget extends StatefulWidget {
State<RouteAwareWidget> createState() => RouteAwareWidgetState();
}
// Implement RouteAware in a widget's state and subscribe it to the RouteObserver.
class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware {
@override
void didChangeDependencies() {
super.didChangeDependencies();
routeObserver.subscribe(this, ModalRoute.of(context));
}
@override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}
@override
void didPush() {
// Route was pushed onto navigator and is now topmost route.
}
@override
void didPopNext() {
// Covering route was popped off the navigator.
}
@override
Widget build(BuildContext context) => Container();
}
This is a more detailed help guide. https://medium.com/flutter-community/how-to-track-screen-transitions-in-flutter-with-routeobserver-733984a90dea
Most of the time you don't need to implement NavigatorObserver
. See this other StackOverflow answer explaining how to use push
and pop
to pass information between routes. In the use case you've described, you should addListener
to an AnimationController
, using the TickerProviderStateMixin
to obtain a suitable vsync
object. This ensures that your callback will not fire when the app is suspended or after your State
is disposed. (Instead of addListener
, you could use an AnimatedBuilder
or AnimatedWidget
the primary purpose of your callback is to rebuild a section of the widget tree.)
The main time when you'd want a NavigatorObserver
is if you're using a plugin like Firebase Analytics. You can see an example usage in the plugins repo. You pass the NavigatorObserver
in the navigatorObservers
argument to the MaterialApp
constructor:
static FirebaseAnalyticsObserver observer =
new FirebaseAnalyticsObserver(analytics: analytics);
...
return new MaterialApp(
navigatorObservers: <NavigatorObserver>[observer],
...
);
It is unusual to have a State
that implements NavigatorObserver
because your MaterialApp
should be near the top of the widget hierarchy. At the time you're constructing it, most State
objects won't exist yet so you'll have a hard time putting them into the navigatorObservers
array. You might instead use a class that isn't a State
. If necessary, you can use GlobalKey<MyClassState>
to find the State
that needs to be notified (but if you're doing this, there might be an easier way to accomplish what you want).