最近刚接触Flutter,在进行页面通用数据管理的时候自然会想到使用Redux,好在已经有大神写好了Dart版的Redux,添加到包里即可。package地址

随着项目的迭代更新,数据只会越来越多,数据也必须采用模块化管理,否则后期的维护简直是地狱。

store目录

redux的数据统一存放在store目录下,目录结构如下

store目录.png

  • index.dart store数据入口
  • app 管理所有state和分发reducer
  • module 模块化的数据

module

先从每个模块开始,每个模块分为actionreducerstate。以mainPage为例,这个模块对应创建项目后自带的计数器演示。

action.dart

class IncreaseAction {
  
}

定义一个action

reducer.dart

import 'package:redux/redux.dart';
import 'package:demo/store/module/mainPage/state.dart';
import 'package:demo/store/module/mainPage/action.dart';

final mainPageReducer = combineReducers<MainPageState>([
  TypedReducer<MainPageState,IncreaseAction>(_increase)
]);

MainPageState _increase (MainPageState state, IncreaseAction action) {
  state.counter += 1;
  return state;
}

这里combineReducers的作用是把action和函数绑定起来,免去了写例如if (action is IncreaseAction)之类的判断语句。对应的action执行对应的函数。

state.dart

class MainPageState {
  int counter;
  MainPageState({
    this.counter: 0
  });

  factory MainPageState.initial() {
    return new MainPageState(
      counter: 0
    );
  }

}

状态类就不用多说了,定义state

这样一个模块就写好了

app

app是管理所有模块的地方

AppState.dart

import 'package:demo/store/module/auth/state.dart';
import 'package:demo/store/module/mainPage/state.dart';

class AppState {
  final AuthState authState;
  final MainPageState mainPageState;
  AppState({
    this.authState,
    this.mainPageState
  });

  factory AppState.initial(){
    return AppState(
      authState: AuthState.initial(),
      mainPageState: MainPageState.initial()
    );
  }
}

定义一个AppState的类,引入所有模块的state,访问数据也是通过它来访问。

AppReducer.dart

import 'AppState.dart';
import 'package:demo/store/module/auth/reducer.dart';
import 'package:demo/store/module/mainPage/reducer.dart';


AppState appReducer(AppState state, dynamic action) =>
    new AppState(
        authState: authReducer(state.authState,action),
        mainPageState: mainPageReducer(state.mainPageState,action)
    );

这里分发reducer的方式有点巧妙,不是简单的判断返回。
appReducer的返回值是一个新的AppState,而新的AppState在构造的时候,每个子state又会执行其模块对应的reducer,每个模块的reducer都会接收到其模块对应的state和要执行的action。如果action非本模块的,state保持不变,如果是当前模块的则执行对应函数。最后state再返回构成新的AppState

index.dart

提供一个创建store的方法,在main.dart里调用。

import 'package:redux/redux.dart';
import 'app/AppState.dart';
import 'app/AppReducer.dart';

Store<AppState> createStore() {
  return Store(
    appReducer,
    initialState: AppState.initial()
  );
}

##dispatch

import 'package:demo/store/module/mainPage/action.dart';
...
store.dispatch(IncreaseAction());
···
);

引入对应模块的action.dart,再dispatch需要的action就行了

本文只介绍了如何模块化的使用Redux,关于如何使用Redux建议查看这篇文章Flutter | 状态管理探索篇——Redux(二),一个大神写的通俗易懂的文章。