Flutter tracking current screen name using RouteObserver

Here is a route observer, my_route_observer.dart

import 'package:flutter/material.dart';
import 'package:myapp/analytics.dart';

class MyRouteObserver extends RouteObserver> {
  void _sendScreenView(PageRoute route) {
    var screenName = route.settings.name;

    // set current screen in analytics or somewhere else
    Analytics.setCurrentScreen(screenName);
    print('screenName $screenName');
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    if (route is PageRoute) {
      _sendScreenView(route);
    }
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (newRoute is PageRoute) {
      _sendScreenView(newRoute);
    }
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    if (previousRoute is PageRoute && route is PageRoute) {
      _sendScreenView(previousRoute);
    }
  }
}

Here is how to register the above route observer in your root widget.

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'MyApp',
      navigatorObservers: [MyRouteObserver()],
      initialRoute: /home,
      routes: {
        'home': (context) => const Home(),
        'SecondScreen': (context) => const SecondScreen(),
        'ThirdScreen': (context) => const ThirdScreen(),
      },
    );
  }
}

If the screen is not registered in the routes, make sure to set the `route.settings.name` when pushing it. Otherwise, the screen name will be null because it not set when it is pushed.

Navigator.of(context).push(
  MaterialPageRoute(
    settings: RouteSettings(name: 'FourthScreen'),
    builder: (context) {
      return FourthScreen();
    },
  ),
);

Here is a sample Analytics class that just tracks the current screen.

class Analytics {

  static ScreenName  _currentScreen = ScreenName.home_screen;
  static ScreenName get currentScreen => _currentScreen;

  static setCurrentScreen(ScreenName screenName) {
    _currentScreen = screenName;
  }

}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search