使用Flutter_Redux实现主题切换

1. 添加依赖

dependencies:
flutter_redux: ^0.6.0

2. 定义State

/// 1.定义状态
class AppStates {
ThemeData themeData;
AppStates({this.themeData});
}
/// 2.提供appReducer方法
AppStates appReducer(AppStates states, dynamic action) {
return AppStates(
/// 使用对应的Reducer将states中的状态和action绑定
themeData: themeModeReducer(states.themeData, action),
);
}
/// 3. 可对数据进行拦截处理
final List<Middleware<AppStates>> middleware = [
AppStatesMiddleware(),
];

3. 定义Reducer

/// 1. 提供action
class BrightnessAction {
Brightness brightness;
BrightnessAction(this.brightness);
}
/// 2. 添加改变状态的方法
ThemeData _change(ThemeData themeData, dynamic action) {
themeData = ThemeData(brightness: action.brightness);
return themeData;
}
/// 3.定义Reducer
final themeModeReducer = combineReducers<ThemeData>([
TypedReducer<ThemeData, BrightnessAction>(_change),
]);

4. 在顶层StatefulWidget中初始化Store

final store = Store<AppStates>(
appReducer,
middleware: middleware,
initialState: AppStates(
themeData: ThemeData.dark(),
),
);
@override
Widget build(BuildContext context) {
return StoreProvider<AppStates>(
store: store,
child: StoreBuilder<AppStates>(builder: (context, store) {
return MaterialApp(
/// 从store中取出当前主题数据
theme: store.state.themeData,
home: MyHomePage(),
);
}),
);
}

5. 修改主题

FlatButton(
onPressed: () {
// 执行dispatch来改变数据的状态
store.dispatch(BrightnessAction(
store.state.themeData.brightness == Brightness.dark
? Brightness.light
: Brightness.dark));
},
child: Text('切换主题'),
),

6.拦截器

class AppStatesMiddleware implements MiddlewareClass<AppStates> {
@override
void call(Store<AppStates> store, action, next) {
// 判断action类型
if(action is BrightnessAction){
// 进行拦截处理
}
// 继续执行
next(action);
}
}
posted @   前端小鑫同学  阅读(8)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示