towhid
towhid

Reputation: 3298

How to get top most screens route name

I am following this Navigate with named routes. Where I am passing a route name to view the new screen.

Navigator.pushNamed(context, '/second');

So, what I need is the topmost screens routeName. in this case /second. How can I get it?

Upvotes: 0

Views: 1850

Answers (3)

Shahar Hajdu
Shahar Hajdu

Reputation: 473

You can register as an observer in navigatorObservers in MaterialApp to get notified when routes change, and keep the last one:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'test',
      home: const MyHomePage(),
      navigatorObservers: [
        RouteObserver(),
      ],
    );
  }
}

class RouteObserver extends NavigatorObserver {
  String? lastRoute;

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    lastRoute = newRoute?.settings.name;
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    lastRoute = route.settings.name;
  }

  @override    
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    lastRoute = previousRoute?.settings.name;
  }

  @override    
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    lastRoute = previousRoute?.settings.name;
  }
}

Upvotes: 2

ZhangLei
ZhangLei

Reputation: 413

String? getTopRouteName (BuildContext context) {
  String? top;
  Navigator.popUntil(context, (route) {
    top = route.settings.name;
    return true;
  });
  return top;
}

Unfortunately, Navigator does not provide such API. But the top most route name could be found through this tricky method, which is trying to pop the top most route, but prevented by the return value true.

Upvotes: 2

Yadu
Yadu

Reputation: 3305

other than Modal.of(context), flutter doesn't provide any easier way to get the latest route name. but anyone who is using route handling using onRouteGenerated property can do this

class AllRoutes{
  static String _lastRoute = "/";

  static Route onGenerated(RouteSettings settings){
    _lastRoute = settings.name;
    //handle route changes here rather passing the route Map to the App
  }  
  static String get lastRoute=>_lastRoute;
}

and add the static method as the onGenerateRoute property value of the App

MaterialApp(
   onGenerateRoute: AllRoutes.onGenerated,
  )

and get the last route like this

var lastRoute = AllRoutes.lastRoute

You could add this as a extension to Navigator so you could feel at home ;)

Upvotes: 2

Related Questions