Flutter完整开发实战详解(四、 Redux、主题、国际化) _ 掘金技术征文

///主题
ThemeData themeData;

///语言
Locale locale;

///构造方法
GSYState({this.userInfo, this.themeData, this.locale});
}

///创建 Reducer
///源码中 Reducer 是一个方法 typedef State Reducer(State state, dynamic action);
///我们自定义了 appReducer 用于创建 store
GSYState appReducer(GSYState state, action) {
return GSYState(
///通过自定义 UserReducer 将 GSYState 内的 userInfo 和 action 关联在一起
userInfo: UserReducer(state.userInfo, action),

///通过自定义 ThemeDataReducer 将 GSYState 内的 themeData 和 action 关联在一起
themeData: ThemeDataReducer(state.themeData, action),

///通过自定义 LocaleReducer 将 GSYState 内的 locale 和 action 关联在一起
locale: LocaleReducer(state.locale, action),
);
}

如上代码,GSYState 的每一个参数,是通过独立的自定义 Reducer 返回的。比如 themeData 是通过 ThemeDataReducer 方法产生的,ThemeDataReducer 其实是将 ThemeData 和一系列 Theme 相关的 Action 绑定起来,用于和其他参数分开。这样就可以独立的维护和管理 GSYState 中的每一个参数。

继续上面流程,如下代码所示,通过 flutter_reduxcombineReducersTypedReducer,将 RefreshThemeDataAction 类 和 _refresh 方法绑定起来,最终会返回一个 ThemeData 实例。也就是说:用户每次发出一个 RefreshThemeDataAction ,最终都会触发 _refresh 方法,然后更新 GSYState 中的 themeData

import ‘package:flutter/material.dart’;
import ‘package:redux/redux.dart’;

///通过 flutter_redux 的 combineReducers,创建 Reducer
final ThemeDataReducer = combineReducers([
///将Action,处理Action动作的方法,State绑定
TypedReducer<ThemeData, RefreshThemeDataAction>(_refresh),
]);

///定义处理 Action 行为的方法,返回新的 State
ThemeData _refresh(ThemeData themeData, action) {
themeData = action.themeData;
return themeData;
}

///定义一个 Action 类
///将该 Action 在 Reducer 中与处理该Action的方法绑定
class RefreshThemeDataAction {

final ThemeData themeData;

RefreshThemeDataAction(this.themeData);
}

OK,现在我们可以愉悦的创建 Store 了。如下代码所示,在创建 Store 的同时,我们通过 initialState 对 GSYState 进行了初始化,然后通过 StoreProvider 加载了 Store 并且包裹了 MaterialApp至此我们完成了 Redux 中的初始化构建。

void main() {
runApp(new FlutterReduxApp());
}

cla

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值