flutter_redux 状态管理

703 阅读4分钟

redux 组成

  • Store :用于存储和管理State,所有的状态都储存在Store里,Store会放在App顶层
  • Action:用户触发的一种行为
  • Reducer:根据Action产生新的State,State状态是由reducer生成并储存在Store里面的。Store更新状态的时候,并不是更改原来的状态对象,而是将reducer生成的新的状态对象替换掉老的状态对, 过程: 通过发起一个action来告诉Reducer,状态要发生变化了,这是 Reducer会收到 一个action,然后根据收到的action 去匹配action,并且生成新的action并把新的状态放到Store中,Store丢弃了老的状态对象,储存了新的状态对象后,就通知所有使用到了这个状态的View更新(类似setState)

添加依赖

flutter_redux: 0.6.0
redux: 4.0.0

创建State

状态是由reducer生成并储存在Store里面的。Store更新状态的时候,并不是更改原来的状态对象,而是直接将reducer生成的新的状态对象替换掉老的状态对象。所以,我们的状态应该是immutable的 创建State

创建State
import 'package:meta/meta.dart';
/**
 * State中所有属性都应该是只读的
 */
@immutable
class CountState{
  int _count;
  get count => _count;

  CountState(this._count);
}

创建action

/**
 * 定义操作该State的全部Action
 * 这里只有增加count一个动作
 */
enum Action{
  increment
}

创建reducer

/**
 * reducer会根据传进来的action生成新的CountState
 */
CountState reducer(CountState state,action){
  //匹配Action
    if(action == Action.increment){
      return CountState(state.count+1);
    }
    return state;
}

创建store

Store接收一个reducer,以及初始化State,我们想用Redux管理全局的状态的话,需要将store储存在应用的入口才行。而在应用打开时要先初始化一次应用的状态。所以在State中添加一个初始化的函数。

//这段代码写在State中
CountState.initState(){ _count = 0;}
//应用顶层
void main() {
  final store =
      Store<CountState>(reducer, initialState: CountState.initState());
  runApp(new MyApp(store));
}

将Store放入顶层

flutter_redux提供了widget叫做StoreProvider,用法接收一个store,和child Widget。

class MyApp extends StatelessWidget {
  final Store<CountState> store;

  MyApp(this.store);

  @override
  Widget build(BuildContext context) {
    return StoreProvider<CountState>(
      store: store,
      child: new MaterialApp(
        title: 'Flutter Demo',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: TopScreen(),
      ),
    );
  }
}

页面中获取Store中的state

StoreConnector<CountState,int>(
              converter: (store) => store.state.count,
              builder: (context, count) {
                return Text(
                  count.toString(),
                  style: Theme.of(context).textTheme.display1,
                );
              },
            ),
  • 要想获取store我们需要使用StoreConnector<S,ViewModel>。StoreConnector能够通过StoreProvider找到顶层的store。而且能够在state发生变化时rebuilt Widget。
  • 首先这里需要强制声明类型,S代表我们需要从store中获取什么类型的state,ViewModel指的是我们使用这个State时的实际类型。
  • 然后我们需要声明一个converter<S,ViewModel>,它的作用是将Store转化成实际ViewModel将要使用的信息,比如我们这里实际上要使用的是count,所以这里将count提取出来。
  • builder是我们实际根据state创建Widget的地方,它接收一个上下文context,以及刚才我们转化出来的ViewModel,所以我们就只需要把拿到的count放进Text Widget中进行渲染就好了。 主要是这个 www.jianshu.com/p/5d7e2dbda…

接受store就比较简单了 在这里插入图片描述 外层用一个StoreProvide,里面如下图 又一个StoreConnector 当然也可以用StoreBuilder 在这里插入图片描述 看看就懂了,但是 我们不这样用 !!!!!

在前面提到创建store,在这里我们这样做,放在main.dart里面,我们看看store 的构造方法

在这里插入图片描述 构造里面需要一个 reducer、State、 middleware 。同时泛型约束为,那我们就在构造方法中传入 State 在这里插入图片描述 我们看看appReducer 和 MainState是怎么实现的 reducer的作用是根据Action产生新的State, 在这里插入图片描述 不是根据action生成state吗 怎么现在这个?那我们看看Reducer的源码 在这里插入图片描述 其实,其实就是appReducer 就是一个reducer。不同的是,我们把很多状态放在一起,统一做多个状态的管理, 至于MainState就什么东西了,就是里面定义了不同的状态 在这里插入图片描述 但是,里面的不同状态很重要,我们看这UserState 在这里插入图片描述 UserInfoModel 和ConnectState看代码没什么好说的

class UserInfoModel {
  int id;
  int gender;

  UserInfoModel({this.id, this.gender});

factory UserInfoModel.fromJson(Map<String, dynamic> json) =>
UserInfoModel(
id: json['id'] as int,
    gender: json['gender'] as int,
);

Map<String, dynamic> toJson() => <String, dynamic> {
  'id': id,
  'gender': gender,
};
}

关键在combineReducers和TypedReducer 比较重点,我们看看这俩 combineReducers: 看下源码 在这里插入图片描述 里面就是放一堆列表作用。combineReducers 辅助函数的作用是,把一个由多个不同 reducer 函数作为 value 的 object,合并成一个最终的 reducer 函数 合并后的 reducer 可以调用各个子 reducer,并把它们的结果合并成一个 state 对象。state 对象的结构由传入的多个 reducer 的 key 决定。

然后怎么发送action使用呢 ? 如图 在这里插入图片描述 这是一个公共的工具类,所有的store都在这里,然后调用 store.dispatch(Action action)就可以发送action了,

TypedReducer官方的意思是说用来根据action过滤执行指定的reducer,那就很明白了, 整个流程 1.创建store 传入 appReducer和 MainState,appReducer生成新的MainState, 2. 看看MainState 里面 就是创建不同的reducer。不同的是这里根据combineReducers和TypedReducer 来根据不同的action ,来创建不同的状态(可以理解不同的状态对应不同更新ui的操作) 3. 然后接受和上面没什么不同,我用的StoreBuilder