zl程序教程

您现在的位置是:首页 >  Java

当前栏目

使用Flutter_Redux实现主题切换

2023-02-18 16:39:32 时间

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);
  }
  
}