alibaba / fish-redux

An assembled flutter application framework.
https://github.com/alibaba/fish-redux
Apache License 2.0
7.33k stars 843 forks source link

关于页面生命周期viewWillAppear #666

Open liumengdi666 opened 4 years ago

liumengdi666 commented 4 years ago

iOS native有提供viewWillAppear方法,在页面每次即将出现的时候调用,但我发现fish-redux并没有类似这样的方法,请问有没有办法可以监听到page即将出现/即将消失的方法,比如从某个页面(native/flutter)pop回来?

ghost commented 4 years ago

一种实现思路,仅供参考。

  1. 页面初始化逻辑,直接在initState中处理。

  2. 页面销毁逻辑,直接在dispose中处理。

  3. 页面重新回到栈顶时需要的刷新/重制逻辑,则通过以下手段实现。

监测Navigator,有路由事件时,广播该事件。需要刷新逻辑的页面注册路由事件,判断路由url是否 为自身,是则进行刷新。

注意点:若导航栈中存在一个页面的多个实例,需要做区分。

class UHRouteObserver extends RouteObserver<PageRoute<dynamic>> {
  void _changePage(PageRoute<dynamic> route, UHRouteAction action) {
    final pageUrl = route.settings.name;
    final model = UHRouteObserverModel(pageUrl, action);
    UHBroadcast.broadcast(
        UHBroadcastActionCreator.onBroadcastChangePage(model));
  }

  @override
  void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
    super.didPush(route, previousRoute);

    if (route is PageRoute) {
      _changePage(route, UHRouteAction.push);
    }
  }

  @override
  void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);

    if (newRoute is PageRoute) {
      _changePage(newRoute, UHRouteAction.replace);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
    super.didPop(route, previousRoute);

    if (previousRoute is PageRoute && route is PageRoute) {
      _changePage(previousRoute, UHRouteAction.pop);
    }
  }
}