flutter_redux的入门级使用

1,285 阅读1分钟

flutter_redux的入门级使用

dependencies:
  flutter_redux: ^0.5.3

Redux

//reducer 核心代码
// int state = 0;
// 开始这里是一个数字
// 如果他是一个对象怎么样
// 单向闭环

//count 状态
class CountState {
  int _count = 0;
  get count => _count;

  String _username = '';
  get username => _username ;

  //状态初始化
  CountState.initState() {
    this._count = 0;
    this._username = '';
  }
  //state构造函数
  CountState(this._count,this._username);
}

//枚举actions
enum AllActions { Increment, SetUserName }

//reducer
CountState counterReducer(CountState state, dynamic action) {
  // reducer 是一个纯函数

  //store.dispatch() 传入了一个数组
  // 第一个参数是actionstype
  var actionsType = action[0];
  //第二个参数是要更改的新数据
  var actionArgments = action[1];
  //分支选择
  switch (actionsType) {
    case AllActions.Increment:
      //修改状态返回新的状态去覆盖原来的状态
      state._count += 100;
      state._username = actionArgments;
      return state;
  }
  return state;
}

Widget代码部分

floatingActionButton: new StoreConnector<CountState, VoidCallback>(
  //converter转换器 在转换器里面调用actions
  converter: (store) {
    return () => store.dispatch([AllActions.Increment,'张三']);
    //传值和通知reducer
  },
  //构造按钮
  builder: (context, callback) {
    return new FloatingActionButton(
      onPressed: callback,
      //这里的callback就是上面的转换器
      ///你也可以这样写
      ///onPressed:(callback){
      /// callback();
      /// //TODO
      ///}
      tooltip: 'Increment',
      child: new Icon(Icons.add),
    );
  },
),

读取store里面状态

StoreConnector<CountState, String>(
  converter: (store) => store.state.count.toString(),
  builder: (context, count) {
    //设置count
    return Text(count);
  },
),
StoreConnector<CountState, String>(
  converter: (store) => store.state.username.toString(),
  builder: (context, username) {
    //设置username
    return Text(username);
  },
),

你需要在main函数里面传递Store


void main () {
final store = new Store<CountState>(counterReducer, initialState: CountState.initState());

  runApp(new MyApp(
    title: 'Flutter Redux Demo',
    store: store,
  ));
}