颤动|如何监听导航事件?

问题描述 投票:0回答:1

在Flutter中,有没有办法监听导航变化?

示例:导航在

Widget A
中触发:

Navigator.of(context).pushNamed('/chat');

执行上述代码时,我希望在

Widget A
的子级中触发一个事件。这可能吗?

flutter
1个回答
9
投票

使用RouteObserver:

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

然后将其添加到根materialApp小部件:

MaterialApp(
      theme: ThemeData(),
      navigatorObservers: [routeObserver],
)

我们需要在每个可能推送或弹出到路由堆栈中的小部件中实现 RouteAware。

class Screen extends State<Screen3> with RouteAware{
...

 @override
 void didChangeDependencies() {
   super.didChangeDependencies();
   routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute<dynamic>);
 }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    final route = ModalRoute.of(context)?.settings.name;
    print('didPush route: $route');
  }

  @override
  void didPopNext() {
    final route = ModalRoute.of(context)?.settings.name;
    print('didPopNext route: $route');
  }

  @override
  void didPushNext() {
    final route = ModalRoute.of(context)?.settings.name;
    print('didPushNext route: $route');
  }

  @override
  void didPop() {
    final route = ModalRoute.of(context)?.settings.name;
    print('didPop route: $route');
  }
...
}
© www.soinside.com 2019 - 2024. All rights reserved.