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); |
| } |
| |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)