Flutter狀態(tài)管理之路(五)

接上一篇Flutter狀態(tài)管理之路(四)
此篇主要介紹flutter_mobx

Fish Redux

版本:0.2.7

庫地址:https://github.com/alibaba/fish-redux/

演進(jìn)過程

閑魚fish_redux演進(jìn)過程1.png
閑魚fish_redux演進(jìn)過程2.png

概念

對象 說明 所屬庫
Action 表示一種意圖,包含兩個(gè)字段<br />type,payload
Connector 表達(dá)了如何從一個(gè)大數(shù)據(jù)中讀取小數(shù)據(jù),<br />同時(shí)對小數(shù)據(jù)的修改如何同步給大數(shù)據(jù)凄鼻,這樣的數(shù)據(jù)連接關(guān)系
Reducer 一個(gè)上下文無關(guān)的 pure function
State 狀態(tài)值
Middleware 中間件蘸鲸,以AOP面向切面形式注入邏輯
Component 對視圖展現(xiàn)和邏輯功能的封裝
Effect 處理Action的副作用
Dependent 表達(dá)了小組件|小適配器是如何連接到 大的Component 的
Page 繼承Component瓷叫,針對頁面級(jí)的抽象,內(nèi)置一個(gè)Store(子Component共享)

使用

例子來源官方 Todos

  1. 入口路由配置

    /// 創(chuàng)建應(yīng)用的根 Widget
    /// 1. 創(chuàng)建一個(gè)簡單的路由忘分,并注冊頁面
    /// 2. 對所需的頁面進(jìn)行和 AppStore 的連接
    /// 3. 對所需的頁面進(jìn)行 AOP 的增強(qiáng)
    Widget createApp() {
      final AbstractRoutes routes = PageRoutes(
        pages: <String, Page<Object, dynamic>>{
          /// 注冊TodoList主頁面
          'todo_list': ToDoListPage(),
    
        },
        visitor: (String path, Page<Object, dynamic> page) {
          /// 只有特定的范圍的 Page 才需要建立和 AppStore 的連接關(guān)系
          /// 滿足 Page<T> 袖裕,T 是 GlobalBaseState 的子類
          if (page.isTypeof<GlobalBaseState>()) {
            /// 建立 AppStore 驅(qū)動(dòng) PageStore 的單向數(shù)據(jù)連接
            /// 1. 參數(shù)1 AppStore
            /// 2. 參數(shù)2 當(dāng) AppStore.state 變化時(shí), PageStore.state 該如何變化
            page.connectExtraStore<GlobalState>(GlobalStore.store,
                (Object pagestate, GlobalState appState) {
              /// 根據(jù)appState變化pagestate
              return pagestate;
            });
          }
    
          /// AOP
          /// 頁面可以有一些私有的 AOP 的增強(qiáng), 但往往會(huì)有一些 AOP 是整個(gè)應(yīng)用下玛界,所有頁面都會(huì)有的。
          /// 這些公共的通用 AOP 悼吱,通過遍歷路由頁面的形式統(tǒng)一加入脚仔。
          page.enhancer.append(
            ...
    
            /// Store AOP
            middleware: <Middleware<dynamic>>[
              logMiddleware<dynamic>(tag: page.runtimeType.toString()),
            ],
          );
        },
      );
    
      return MaterialApp(
        title: 'Fluro',
        home: routes.buildPage('todo_list', null),
        onGenerateRoute: (RouteSettings settings) {
          return MaterialPageRoute<Object>(builder: (BuildContext context) {
            return routes.buildPage(settings.name, settings.arguments);
          });
        },
      );
    }
    
  2. 新建Page

class ToDoListPage extends Page<PageState, Map<String, dynamic>> {
  ToDoListPage()
      : super(
          initState: initState,
          effect: buildEffect(),
          reducer: buildReducer(),
          view: buildView,
        );
}
  1. 定義state
class PageState extends MutableSource
    implements GlobalBaseState, Cloneable<PageState> {
  List<ToDoState> toDos;

  @override
  Color themeColor;

  @override
  PageState clone() {
    return PageState()
      ..toDos = toDos
      ..themeColor = themeColor;
  }

  @override
  Object getItemData(int index) => toDos[index];

  @override
  String getItemType(int index) => 'toDo';

  @override
  int get itemCount => toDos?.length ?? 0;

  @override
  void setItemData(int index, Object data) => toDos[index] = data;
}

PageState initState(Map<String, dynamic> args) {
  //just demo, do nothing here...
  return PageState();
}
  1. 定義Action
enum PageAction { initToDos, onAdd }

class PageActionCreator {
  static Action initToDosAction(List<ToDoState> toDos) {
    return Action(PageAction.initToDos, payload: toDos);
  }

  static Action onAddAction() {
    return const Action(PageAction.onAdd);
  }
}
  1. 定義Reducer
Reducer<PageState> buildReducer() {
  return asReducer(
    <Object, Reducer<PageState>>{PageAction.initToDos: _initToDosReducer},
  );
}

PageState _initToDosReducer(PageState state, Action action) {
  final List<ToDoState> toDos = action.payload ?? <ToDoState>[];
  final PageState newState = state.clone();
  newState.toDos = toDos;
  return newState;
}

  1. 定義Effect
Effect<PageState> buildEffect() {
  return combineEffects(<Object, Effect<PageState>>{
    Lifecycle.initState: _init,
    PageAction.onAdd: _onAdd,
  });
}

void _init(Action action, Context<PageState> ctx) {
  final List<ToDoState> initToDos = <ToDoState>[];
  /// 可作網(wǎng)絡(luò)/IO等耗時(shí)操作
  ctx.dispatch(PageActionCreator.initToDosAction(initToDos));
}

void _onAdd(Action action, Context<PageState> ctx) {
  Navigator.of(ctx.context)
      .pushNamed('todo_edit', arguments: null)
      .then((dynamic toDo) {
    if (toDo != null &&
        (toDo.title?.isNotEmpty == true || toDo.desc?.isNotEmpty == true)) {
      ctx.dispatch(list_action.ToDoListActionCreator.add(toDo));
    }
  });
}
  1. 定義View視圖
Widget buildView(PageState state, Dispatch dispatch, ViewService viewService) {
  return Scaffold(
    appBar: AppBar(
      backgroundColor: state.themeColor,  /// 獲取state狀態(tài)
      title: const Text('ToDoList'),
    ),
    body: Container(
      child: Column(
        children: <Widget>[
        
        ],
      ),
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: () => dispatch(PageActionCreator.onAddAction()),  /// 發(fā)出意圖改變狀態(tài)
      tooltip: 'Add',
      child: const Icon(Icons.add),
    ),
  );
}

組裝子Component

  1. 定義state
class ReportState implements Cloneable<ReportState> {
  int total;
  int done;

  ReportState({this.total = 0, this.done = 0});

  @override
  ReportState clone() {
    return ReportState()
      ..total = total
      ..done = done;
  }

}

  1. 定義Component
class ReportComponent extends Component<ReportState> {
  ReportComponent()
      : super(
          view: buildView,
        );
}
  1. 定義視圖
Widget buildView(
  ReportState state,
  Dispatch dispatch,
  ViewService viewService,
) {
  return Container(
      margin: const EdgeInsets.all(8.0),
      padding: const EdgeInsets.all(8.0),
      color: Colors.blue,
      child: Row(
        children: <Widget>[
          Container(
            child: const Icon(Icons.report),
            margin: const EdgeInsets.only(right: 8.0),
          ),
          Text(
            'Total ${state.total} tasks, ${state.done} done.',
            style: const TextStyle(fontSize: 18.0, color: Colors.white),
          )
        ],
      ));
}
  1. 定義Connector來連接父子Component
class ReportConnector extends ConnOp<PageState, ReportState>
    with ReselectMixin<PageState, ReportState> {
  @override
  ReportState computed(PageState state) {
    return ReportState()
      ..done = state.toDos.where((ToDoState tds) => tds.isDone).length
      ..total = state.toDos.length;
  }

  @override
  void set(PageState state, ReportState subState) {
    throw Exception('Unexcepted to set PageState from ReportState');
  }
}
  1. page中使用,改造page如下
class ToDoListPage extends Page<PageState, Map<String, dynamic>> {
  ToDoListPage()
      : super(
          initState: initState,
          effect: buildEffect(),
          reducer: buildReducer(),
          view: buildView,
          dependencies: Dependencies<PageState>(
              slots: <String, Dependent<PageState>>{
                'report': ReportConnector() + ReportComponent()
              }),
        );
}
  1. page的buildView改造如下
Widget buildView(PageState state, Dispatch dispatch, ViewService viewService) {
  final ListAdapter adapter = viewService.buildAdapter();
  return Scaffold(
    appBar: AppBar(
      backgroundColor: state.themeColor,
      title: const Text('ToDoList'),
    ),
    body: Container(
      child: Column(
        children: <Widget>[
          viewService.buildComponent('report'),   /// 加載子Component
        ],
      ),
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: () => dispatch(PageActionCreator.onAddAction()),
      tooltip: 'Add',
      child: const Icon(Icons.add),
    ),
  );
}

關(guān)鍵對象

Middleware

StoreMiddleware舆绎,實(shí)際是對Store的dispatch函數(shù)進(jìn)行加強(qiáng)

store_middleware.png
/// fish-redux-master/lib/src/redux/apply_middleware.dart
StoreEnhancer<T> applyMiddleware<T>(List<Middleware<T>> middleware) {
  return middleware == null || middleware.isEmpty
      ? null
      : (StoreCreator<T> creator) => (T initState, Reducer<T> reducer) {
            final Store<T> store = creator(initState, reducer);
            final Dispatch initialValue = store.dispatch;   /// 原始的dispatch
            store.dispatch = middleware
                .map((Middleware<T> middleware) => middleware(   /// 執(zhí)行middleware最外層函數(shù)返回Composable<T>,此函數(shù)在這里用于對dispatch包裝
                      dispatch: (Action action) => store.dispatch(action),
                      getState: store.getState,
                    ))
                .fold(
                  initialValue,
                  (Dispatch previousValue,
                          Dispatch Function(Dispatch) element) =>
                      element(previousValue),       /// 每次將上一個(gè)dispatch傳入们颜,返回一個(gè)新的dispatch吕朵,利用閉包,新的dispatch持有了上一個(gè)dispatch的引用
                );

            return store;
          };
}

其中某一個(gè)Middleware示例如下:

Middleware<T> logMiddleware<T>({
  String tag = 'redux',
  String Function(T) monitor,
}) {
  return ({Dispatch dispatch, Get<T> getState}) {
    return (Dispatch next) {   /// 此方法在上一個(gè)示意代碼段里猎醇,是fold方法里的element
      return isDebug()
          ? (Action action) {   /// 返回包裝的Dispatch
              print('---------- [$tag] ----------');
              print('[$tag] ${action.type} ${action.payload}');

              final T prevState = getState();
              if (monitor != null) {
                print('[$tag] prev-state: ${monitor(prevState)}');
              }

              next(action);

              final T nextState = getState();
              if (monitor != null) {
                print('[$tag] next-state: ${monitor(nextState)}');
              }
            }
          : next;
    };
  };
}

全局Store

fish_redux_全局store時(shí)序圖.png
 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;
        });

Connector

fish_redux_connector_reducer.png
abstract class MutableConn<T, P> implements AbstractConnector<T, P> {
  const MutableConn();

  void set(T state, P subState);

  @override
  SubReducer<T> subReducer(Reducer<P> reducer) {
    /// 將本Component的reducer包裝成新的reducer給父的store注入
    return (T state, Action action, bool isStateCopied) {
      final P props = get(state);
      if (props == null) {
        return state;
      }
      final P newProps = reducer(props, action);  /// 調(diào)用本Component的reducer,返回子的state
      final bool hasChanged = newProps != props;
      final T copy = (hasChanged && !isStateCopied) ? _clone<T>(state) : state;
      if (hasChanged) {
        set(copy, newProps);  /// 通知父Component同步狀態(tài)
      }
      return copy;
    };
  }
}

其余詳見官方文檔:https://github.com/alibaba/fish-redux/blob/master/doc/README-cn.md

總結(jié)

優(yōu)點(diǎn):

  1. 每個(gè)Page一個(gè)Store,子Component共享其Store努溃,單個(gè)Component仍擁有redux的特性以實(shí)現(xiàn)分治
  2. 子的reducer自動(dòng)合并硫嘶,與page的store自動(dòng)進(jìn)行數(shù)據(jù)同步
  3. 利用eventbus 建立page之間的聯(lián)系,通過broadcast effect來分發(fā)page自身不關(guān)心的Action給其它page
  4. 可以全局共享狀態(tài)梧税,定義一個(gè)全局Store在用page.connectExtraStore關(guān)聯(lián)

缺點(diǎn):

  1. 概念較多沦疾,學(xué)習(xí)曲線較高
  2. 需要定義的各類對象多、文件多
  3. 對項(xiàng)目規(guī)模把握不到位容易引入不必要的復(fù)雜度
  4. 代碼結(jié)構(gòu)侵入性較大

未完待續(xù)

fish_redux框架定義的概念很多第队,還需要繼續(xù)深入...

參考

  1. 手把手入門Fish-Redux開發(fā)flutter
  2. Connector的實(shí)現(xiàn)原理
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末哮塞,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子凳谦,更是在濱河造成了極大的恐慌忆畅,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,590評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件尸执,死亡現(xiàn)場離奇詭異家凯,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)如失,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門绊诲,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人褪贵,你說我怎么就攤上這事掂之。” “怎么了竭鞍?”我有些...
    開封第一講書人閱讀 169,301評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵板惑,是天一觀的道長。 經(jīng)常有香客問我偎快,道長冯乘,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評(píng)論 1 300
  • 正文 為了忘掉前任晒夹,我火速辦了婚禮裆馒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘丐怯。我一直安慰自己喷好,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評(píng)論 6 398
  • 文/花漫 我一把揭開白布读跷。 她就那樣靜靜地躺著梗搅,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上无切,一...
    開封第一講書人閱讀 52,682評(píng)論 1 312
  • 那天荡短,我揣著相機(jī)與錄音,去河邊找鬼哆键。 笑死掘托,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的籍嘹。 我是一名探鬼主播闪盔,決...
    沈念sama閱讀 41,155評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼辱士!你這毒婦竟也來了泪掀?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,098評(píng)論 0 277
  • 序言:老撾萬榮一對情侶失蹤识补,失蹤者是張志新(化名)和其女友劉穎族淮,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體凭涂,經(jīng)...
    沈念sama閱讀 46,638評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡祝辣,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了切油。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蝙斜。...
    茶點(diǎn)故事閱讀 40,852評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖澎胡,靈堂內(nèi)的尸體忽然破棺而出孕荠,到底是詐尸還是另有隱情,我是刑警寧澤攻谁,帶...
    沈念sama閱讀 36,520評(píng)論 5 351
  • 正文 年R本政府宣布稚伍,位于F島的核電站,受9級(jí)特大地震影響戚宦,放射性物質(zhì)發(fā)生泄漏个曙。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評(píng)論 3 335
  • 文/蒙蒙 一受楼、第九天 我趴在偏房一處隱蔽的房頂上張望垦搬。 院中可真熱鬧,春花似錦艳汽、人聲如沸猴贰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽米绕。三九已至瑟捣,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間义郑,已是汗流浹背蝶柿。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評(píng)論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留非驮,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,279評(píng)論 3 379
  • 正文 我出身青樓雏赦,卻偏偏與公主長得像劫笙,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子星岗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容