alibaba/fish-redux

对于pageView中的子页面,如何优雅的连接全局的状态?

Open

#549 opened on Nov 28, 2019

View on GitHub
 (6 comments) (0 reactions) (0 assignees)Dart (837 forks)batch import
enhancementgood first issue

Repository metrics

Stars
 (7,281 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

看了fish-redux的todoList demo,发现里面连接全局状态的方法是使用visitor

visitor: (String path, Page<Object, dynamic> page) {
      /// 只有特定的范围的 Page 才需要建立和 AppStore 的连接关系
      /// 满足 Page<T> ,T 是 GlobalBaseState 的子类
      if (page.isTypeof<GlobalBaseState>()) {
        /// 建立 AppStore 驱动 PageStore 的单向数据连接
        /// 1. 参数1 AppStore
        /// 2. 参数2 当 AppStore.state 变化时, PageStore.state 该如何变化
        page.connectExtraStore<GlobalState>(GlobalStore.store,
            (Object pagestate, GlobalState appState) {
          final GlobalBaseState p = pagestate;
          if (p.themeColor != appState.themeColor) {
            if (pagestate is Cloneable) {
              final Object copy = pagestate.clone();
              final GlobalBaseState newState = copy;
              newState.themeColor = appState.themeColor;
              return newState;
            }
          }
          return pagestate;
        });
      }

但是pageview的子页面是由 AccountPage().buildPage(null)这种方式生成的,并不会触发visitor的回调。


Widget pageViewItemBuilder(BuildContext context, int index) {
  if (index == 0) {
    return AccountPage().buildPage(null);
  } else if (index == 1) {
    return TranscationPage().buildPage(null);
  } else if (index == 2) {
    return PersonPage().buildPage(null);
  }
  return Text('页面跳转错误');

}

为了解决这个问题,我在page的构造方法中连接了全局状态。


    this.connectExtraStore<GlobalState>(GlobalStore.store,
        (Object pageState, GlobalState appState) {
      debugPrint('克隆该页面');

      if (pageState is Cloneable) {
        final Object copy = pageState.clone();
        final GlobalAccountBaseState newState = copy;
        newState.totalAssets = appState.totalAssets;
        newState.netAssets = appState.netAssets;
        newState.debt = appState.debt;
        return newState;
      }
      return pageState;
    });

请问是否有更加好的解决办法

Contributor guide