所以一般流程为:
1、Widget 绑定了 Store 中的 state 数据。
2、Widget 通过 Action 发布一个动作。
3、Reducer 根据 Action 更新 state。
4、更新 Store 中 state 绑定的 Widget。
根据这个流程,首先我们要创建一个 Store 。如下图,创建 Store 需要 reducer
,而 reducer
实际上是一个带有 state
和 action
的方法,并返回新的 State 。
所以我们需要先创建一个 State 对象 GSYState
类,用于储存需要共享的数据。比如下方代码的: 用户信息、主题、语言环境 等。
接着我们需要定义 Reducer 方法 appReducer
:将 GSYState
内的每一个参数,和对应的 action
绑定起来,返回完整的 GSYState
。这样我们就确定了 State 和 Reducer 用于创建 Store。
///全局Redux store 的对象,保存State数据
class GSYState {
///用户信息
User userInfo;
///主题
ThemeData themeData;
///语言
Locale locale;
///构造方法
GSYState({this.userInfo, this.themeData, this.locale});
}
///创建 Reducer
///源码中 Reducer 是一个方法 typedef State Reducer(State state, dynamic action);
///我们自定义了 appReducer 用于创建 store
GSYState appReducer(GSYState state, action) {
return GSYState(
///通过自定义 UserReducer 将 GSYState 内的 userInfo 和 action 关联在一起
userInfo: UserReducer(state.userInfo, action),
///通过自定义 ThemeDataReducer 将 GSYState 内的 themeData 和 action 关联在一起
themeData: ThemeDataReducer(state.themeData, action),
///通过自定义 LocaleReducer 将 GSYState 内的 locale 和 action 关联在一起
locale: LocaleReducer(state.locale, action),
);
}
如上代码,GSYState 的每一个参数,是通过独立的自定义 Reducer 返回的。比如 themeData
是通过 ThemeDataReducer
方法产生的,ThemeDataReducer
其实是将 ThemeData
和一系列 Theme 相关的 Action 绑定起来,用于和其他参数分开。这样就可以独立的维护和管理 GSYState 中的每一个参数。
继续上面流程,如下代码所示,通过 flutter_redux 的 combineReducers
与 TypedReducer
,将 RefreshThemeDataAction
类 和 _refresh
方法绑定起来,最终会返回一个 ThemeData
实例。也就是说:用户每次发出一个 RefreshThemeDataAction ,最终都会触发 _refresh 方法,然后更新 GSYState 中的 themeData。
import ‘package:flutter/material.dart’;
import ‘package:redux/redux.dart’;
///通过 flutter_redux 的 combineReducers,创建 Reducer
final ThemeDataReducer = combineReducers([
///