Capture Flutter app navigation events
User navigation between app pages is captured in session replay via LogRocketNavigatorObserver
. When registered, the navigator observer captures navigations to and away from pages in apps.
Registering the navigation observer
Register LogRocket's navigation observer on construction of your WidgetsApp
or any of its subclasses, such as MaterialApp
, or directly on any Navigator
instances themselves. Passing a URL host to the navigator observer's constructor will form the base of URLs generated for navigation events.
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return LogRocketWidget(
child: MaterialApp(
title: 'Flutter App',
home: HomePage(),
navigatorObservers: [LogRocketNavigatorObserver('example.com')]
theme: ...
)
);
}
}
Tag pages
Pages can be tagged independently of automatic navigation captures by calling LogRocket.tagPage
, and passing the name of the tagged page. It is recommended that the LogRocket Navigator Observer is registered before pages are tags, as navigation events generated by page tags inherit the navigation observer's URL.
Tagged pages register as the final path segment in a navigation hierarchy. Route pushes and pops on the app will clear any page tag from the navigation observer's URL. If the same page is tagged repeatedly, LogRocket will only log the first instance as a navigation event.
In a stateless widget, the call to tagPage
should be made in the widget's build
method.
Tag pages in a stateful widget
Call tagPage
in a stateful widget from the initState
method in its associated State
object to avoid repetitive navigation events as the stateful widget is re-rendered in response to state changes.
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
void initState() {
super.initState();
LogRocket.tagPage('Home');
}
@override
Widget build(BuildContext context) {
return const Text('Welcome');
}
}
GoRouter
A LogRocketNavigatorObserver
can be registered with GoRouter to observe navigation changes.
final _router = GoRouter(
observers: [LogRocketNavigatorObserver()],
routes: [
// your routes here
],
);
StatefulShellRoute limitations
If your app is using StatefulShellRoutes
, GoRouter has a few limitations that may interfere with navigation tracking. These are discussed in this Flutter GitHub Issue, but the main limitations are as follows:
- When using
StatefulShellRoutes
, top level observers are not notified of URL changes in each stateful child route. - GoRouter does not signal observers when switching between
StatefulShellRoutes
.
Because of these limitations, it may be preferable to manually track navigation via tagPage with the current route. An example of how to do so can be found in our logrocket_flutter
package example under GoRouterStatefulShellSample.