alibaba/fish-redux

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

Open

#549 aperta il 28 nov 2019

Vedi su GitHub
 (6 commenti) (0 reazioni) (0 assegnatari)Dart (837 fork)batch import
enhancementgood first issue

Metriche repository

Star
 (7281 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

看了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;
    });

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

Guida contributor