美文网首页
Flutter 监听页面切换

Flutter 监听页面切换

作者: 旺仔_100 | 来源:发表于2021-09-09 11:10 被阅读0次
    一、背景

    我们经常会遇到从上一个页面回到当前页面去做刷新。但是state的生命周期实际上没有这个监听。当然我们可以通过监听上个页面的返回值,在当前页面await结果来做。但是这种方式还需要在下一个页面去写代码,不解耦。另一种方式就是监听路由。

    二、监听页面切换

    我们会使用到RouteAware这个类,查看源码如下:

    /// An interface for objects that are aware of their current [Route].
    ///
    /// This is used with [RouteObserver] to make a widget aware of changes to the
    /// [Navigator]'s session history.
    abstract class RouteAware {
      /// Called when the top route has been popped off, and the current route
      /// shows up.
      void didPopNext() { }
    
      /// Called when the current route has been pushed.
      void didPush() { }
    
      /// Called when the current route has been popped off.
      void didPop() { }
    
      /// Called when a new route has been pushed, and the current route is no
      /// longer visible.
      void didPushNext() { }
    }
    

    举个栗子:
    加入当前有三个页面,A、B、C,我们从A调到B跳到C,再从C回到B回到A。依次会对应下面几个方法回调。

    • didpush 当A打开到B的时候回调
    • didPushNext 当B打开C的时候回调
    • didPopNext 当C回到B的时候回调
    • didPop 当B关闭回到A的时候调用
    三、具体使用

    1.创建一个RouteObserver

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

    2.在MaterialApp中navigatorObservers属性添加routeObserver

    MaterialApp(
    ...
    navigatorObservers: [routeObserver],
    ...
    

    3.在使用的State类上混入RouteAware

    class AddressListPageState extends State<AddressListPage> with RouteAware{
    

    4.在didChangeDependencies中去注册监听和在dispose中注销。注意两点,一是不要在initState中注册,会报错。二是flutter2.0之后需要强转成PageRoute。

     @override
      void didChangeDependencies() {
        routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
        super.didChangeDependencies();
      }
    
      @override
      void dispose() {
        print("dispose");
        routeObserver.unsubscribe(this);
        super.dispose();
      }
    

    5.实现对应的监听回调

     @override
      void didPop() {
        ///从B退回到A的是调用
        print("didPop");
        super.didPop();
      }
    
      @override
      void didPush() {
        ///从A进入B的时候调用
        print("didPush");
    
        super.didPush();
      }
    
      @override
      void didPopNext() {
        ///从C回到B的时候调用
        print("didPopNext");
        super.didPopNext();
      }
    
      @override
      void didPushNext() {
        ///从B进入C的时候调用
        print("didPushNext");
        super.didPushNext();
      }
    

    相关文章

      网友评论

          本文标题:Flutter 监听页面切换

          本文链接:https://www.haomeiwen.com/subject/jmsiwltx.html