接上一篇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
-
入口路由配置
/// 創(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); }); }, ); }
新建Page
class ToDoListPage extends Page<PageState, Map<String, dynamic>> {
ToDoListPage()
: super(
initState: initState,
effect: buildEffect(),
reducer: buildReducer(),
view: buildView,
);
}
- 定義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();
}
- 定義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);
}
}
- 定義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;
}
- 定義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));
}
});
}
- 定義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
- 定義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;
}
}
- 定義Component
class ReportComponent extends Component<ReportState> {
ReportComponent()
: super(
view: buildView,
);
}
- 定義視圖
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),
)
],
));
}
- 定義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');
}
}
- 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()
}),
);
}
- 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):
- 每個(gè)Page一個(gè)Store,子Component共享其Store努溃,單個(gè)Component仍擁有redux的特性以實(shí)現(xiàn)分治
- 子的reducer自動(dòng)合并硫嘶,與page的store自動(dòng)進(jìn)行數(shù)據(jù)同步
- 利用eventbus 建立page之間的聯(lián)系,通過broadcast effect來分發(fā)page自身不關(guān)心的Action給其它page
- 可以全局共享狀態(tài)梧税,定義一個(gè)全局Store在用page.connectExtraStore關(guān)聯(lián)
缺點(diǎn):
- 概念較多沦疾,學(xué)習(xí)曲線較高
- 需要定義的各類對象多、文件多
- 對項(xiàng)目規(guī)模把握不到位容易引入不必要的復(fù)雜度
- 代碼結(jié)構(gòu)侵入性較大
未完待續(xù)
fish_redux框架定義的概念很多第队,還需要繼續(xù)深入...