///主题
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([
///将Action,处理Action动作的方法,State绑定
TypedReducer<ThemeData, RefreshThemeDataAction>(_refresh),
]);
///定义处理 Action 行为的方法,返回新的 State
ThemeData _refresh(ThemeData themeData, action) {
themeData = action.themeData;
return themeData;
}
///定义一个 Action 类
///将该 Action 在 Reducer 中与处理该Action的方法绑定
class RefreshThemeDataAction {
final ThemeData themeData;
RefreshThemeDataAction(this.themeData);
}
OK,现在我们可以愉悦的创建 Store 了。如下代码所示,在创建 Store 的同时,我们通过 initialState
对 GSYState 进行了初始化,然后通过 StoreProvider
加载了 Store 并且包裹了 MaterialApp
。 至此我们完成了 Redux 中的初始化构建。
void main() {
runApp(new FlutterReduxApp());
}
cla