79133000

Date: 2024-10-28 10:40:03
Score: 2.5
Natty:
Report link

A NavigatorObserver can help you monitor route changes throughout the app without relying on the BuildContext.

  1. 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"); } }

  2. 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(), ); } }

  3. 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');

  4. 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");

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Contains question mark (0.5):
  • Unregistered user (0.5):
  • User mentioned (1): @override
  • User mentioned (0): @override
  • User mentioned (0): @override
  • Low reputation (1):
Posted by: Aiden Pearce