在之前的(二)Flutter Redux 中的 combineReducers文章中我们对redux有了初步的认识和使用,这次主要是将 combineReducers 和 系统换肤 结合起来使用。
第一步:声明一个State类
/// 定义一个state
class ReduxState {
ThemeData themeData;
ReduxState({this.themeData});
}
/// 定义action,将action放到theme_redux类里去定义
/// 定义reducer
ReduxState getReduce(ReduxState state, action) {
return ReduxState(
themeData: ThemeDataReducer(state.themeData, action)
);
}
第二步:声明一个处理换肤的Reducer类 theme_redux.dart
/// 换肤Action和函数绑定起来
final ThemeDataReducer = combineReducers<ThemeData>([
TypedReducer<ThemeData, ThemeRefreshAction>(_refreshTheme)
]);
/// 换肤方法
ThemeData _refreshTheme(ThemeData themeData, ThemeRefreshAction action) {
themeData = action.themeData;
return themeData;
}
/// 换肤Action
class ThemeRefreshAction {
ThemeData themeData;
ThemeRefreshAction(this.themeData);
}
第三步:创建全局Store,并将Store跟根Widget关联
main() {
/// 创建全局Store
final store = Store<ReduxState>(
getReduce,
initialState: ReduxState(
/// 初始话默认的皮肤数据
themeData: ThemeData(primaryColor: Colors.black)
)
);
runApp(ReduxDemo3(store,));
}
class ReduxDemo3 extends StatelessWidget {
final Store<ReduxState> store;
ReduxDemo3(this.store);
@override
Widget build(BuildContext context) {
return StoreProvider(
store: store,
/// StoreBuilder后要跟上我们定义的那个State类,要不会报错,
child: StoreBuilder<ReduxState>(builder: (BuildContext context, Store<ReduxState> store){
return MaterialApp(
title: 'ReduxDemo3',
/// 这边的皮肤数据主要从store中去取
theme: store.state.themeData,
home: FirstPage(),
);
})
);
}
}
第四步:界面构建,变更皮肤的同时变更文本颜色
class FirstPageState extends State<FirstPage> {
@override
Widget build(BuildContext context) {
return StoreBuilder<ReduxState>(
builder: (BuildContext context, Store<ReduxState> store){
return Scaffold(
appBar: AppBar(
title: Text("ReduxDemo3"),
),
body: Center(
child: Column(
children: _btnList(store),
)
),
);
}
);
}
/// 构建按钮
_btnList(Store store) {
List<Widget> list = List();
for(int i = 0; i < getThemeListColors().length; i++) {
list.add(SizedBox(height: 20,));
list.add(_buildBtns(store, i));
}
return list;
}
/// 改变皮肤颜色的同时也修改文本的颜色
Widget _buildBtns(Store store, int index) {
return FlatButton(
onPressed: (){
store.dispatch(ThemeRefreshAction(ThemeData(
/// store发出修改皮肤的action
primaryColor: getThemeListColors()[index]
)));
},
child: Text(
getThemeListNames()[index],
style: TextStyle(
/// 文本的颜色从store中获取
color: store.state.themeData.primaryColor
),
)
);
}
/// 颜色值数组
static List<Color> getThemeListColors() {
return [
Colors.black,
Colors.red,
Colors.orange,
Colors.brown,
Colors.blue,
];
}
/// 颜色名数组
static List<String> getThemeListNames() {
return [
"black",
"red",
"orange",
"brown",
"blue",
];
}
}