A NavigatorObserver can help you monitor route changes throughout the app without relying on the BuildContext.
Create a Custom NavigatorObserver
class RouteObserverService extends NavigatorObserver { String? currentRoute;
@override void didPush(Route route, Route? previousRoute) { super.didPush(route, previousRoute); currentRoute = route.settings.name; print("Current Screen: $currentRoute"); }
@override void didPop(Route route, Route? previousRoute) { super.didPop(route, previousRoute); currentRoute = previousRoute?.settings.name; print("Returned to Screen: $currentRoute"); } }
Add the Observer to Your App. Pass the custom observer to the MaterialApp to ensure it tracks navigation changes across the app.
final RouteObserverService routeObserver = RouteObserverService();
void main() { runApp(MyApp()); }
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( navigatorObservers: [routeObserver], home: HomeScreen(), ); } }
Push to screen like below to get the current visible screen name.
// Navigating to Screen using named Navigator.pushNamed(context, '/screenName'); // Navigating to Screen pushing a widget Navigator.push( context, MaterialPageRoute(builder: (context) => DetailsScreen()), settings: RouteSettings( name: '/screenName');
Access the Current Route from Anywhere. Since the RouteObserverService is global, you can access the currentRoute attribute to get the latest screen name from anywhere in the app.
String? currentScreenName = routeObserver.currentRoute; print("Currently Displayed Screen: $currentScreenName");