Flutter获取当前路由信息和全局路由监听


Flutter获取当前路由信息和全局路由监听

获取当前路由名

通过Flutter提供的方式

var routePath = ModalRoute.of(context).settings.name;
print("current route: $name")

通过GetX的方式

var routePath = Get.currentRoute;
print("current route: $name");

PS 必须确保注册了路由,否则无法使获取到

配置全局路由监听

创建一个MyRouteObserver继承RouteObserver类

  • 重写RouteObserver中的方法
class MyRouteObserver> extends RouteObserver {
  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    print(
        'didPush route: ${route.settings.name},  previousRoute:${previousRoute?.settings.name}');
 }

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    print(
        'didPop route: ${route.settings.name},  previousRoute:${previousRoute?.settings.name}');
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    print('didReplace newRoute: $newRoute,oldRoute:$oldRoute');
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    super.didRemove(route, previousRoute);
    print('didRemove route: $route,previousRoute:$previousRoute');
  }

  @override
  void didStartUserGesture(Route route, Route? previousRoute) {
    super.didStartUserGesture(route, previousRoute);
    print('didStartUserGesture route: $route,previousRoute:$previousRoute');
  }

  @override
  void didStopUserGesture() {
    super.didStopUserGesture();
    print('didStopUserGesture');
  }
}
  • 然后在MaterialApp中添加
final MyRouteObserver routeObserver = MyRouteObserver();
MaterialApp(navigatorObservers: routeObserver])

这样就可以监听到所有路由pop,push,remove等动作,并且在其中加入自己的业务逻辑,不管是模态,dialog,bottomsheet都可以监听到。

参考