这里使用了StoreModel中间实体,注意,这地方实体字段store,初始化是必须的,不然在子模块引用该实体下的字段会报空指针
abstract class GlobalBaseState{ StoreModel store; } class GlobalState implements GlobalBaseState, Cloneable<GlobalState>{ @override GlobalState clone() { return GlobalState(); } @override StoreModel store = StoreModel( /// store这个变量,在这必须示例化,不然引用该变量中的字段,会报空指针 /// 下面的字段,赋初值,就是初始时展示的全局状态 /// 这地方初值,理应从缓存或数据库中取,表明用户选择的全局状态 themeColor: Colors.lightBlue ); } ///中间全局实体 ///需要增加字段就在这个实体里面添加就行了 class StoreModel { Color themeColor; StoreModel({this.themeColor}); }reducer
这地方改动非常小,将state.themeColor改成state.store.themeColor
Reducer<GlobalState> buildReducer(){ return asReducer( <Object, Reducer<GlobalState>>{ GlobalAction.changeThemeColor: _onChangeThemeColor, }, ); } List<Color> _colors = <Color>[ Colors.green, Colors.red, Colors.black, Colors.blue ]; GlobalState _onChangeThemeColor(GlobalState state, Action action) { final Color next = _colors[((_colors.indexOf(state.store.themeColor) + 1) % _colors.length)]; return state.clone()..store.themeColor = next; }下面俩个模块代码没有改动,但是为了思路完整,同样贴出来
action
enum GlobalAction { changeThemeColor } class GlobalActionCreator{ static Action onChangeThemeColor(){ return const Action(GlobalAction.changeThemeColor); } }store
class GlobalStore{ static Store<GlobalState> _globalStore; static Store<GlobalState> get store => _globalStore ??= createStore<GlobalState>(GlobalState(), buildReducer()); } 子模块使用这里就用计数器模块的来举例,因为仅仅只需要改动少量代码,且只涉及state和view,所以其它模块代码也不重复贴出了
state
因为是用中间实体,所以在clone方法里面必须将实现的store字段加上,不然会报空指针
class CountState implements Cloneable<CountState>, GlobalBaseState { int count; @override CountState clone() { return CountState() ..count = count ..store = store; } @override StoreModel store; } CountState initState(Map<String, dynamic> args) { return CountState()..count = 0; }view