使用Flutter_Redux实现主题切换

2022-12-24 11:02:59 浏览数 (1)

1. 添加依赖

代码语言:javascript复制
dependencies:
  flutter_redux: ^0.6.0
2. 定义State
代码语言:javascript复制
/// 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
代码语言:javascript复制
/// 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
代码语言:javascript复制
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. 修改主题
代码语言:javascript复制
FlatButton(
    onPressed: () {
      // 执行dispatch来改变数据的状态
      store.dispatch(BrightnessAction(
          store.state.themeData.brightness == Brightness.dark
              ? Brightness.light
              : Brightness.dark));
    },
    child: Text('切换主题'),
  ),
6.拦截器
代码语言:javascript复制
class AppStatesMiddleware implements MiddlewareClass<AppStates> {
  @override
  void call(Store<AppStates> store, action, next) {
    // 判断action类型
    if(action is BrightnessAction){
      // 进行拦截处理
    }
    // 继续执行
    next(action);
  }
  
}

0 人点赞