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

所以一般流程为:

1、Widget 绑定了 Store 中的 state 数据。

2、Widget 通过 Action 发布一个动作。

3、Reducer 根据 Action 更新 state。

4、更新 Store 中 state 绑定的 Widget。

根据这个流程,首先我们要创建一个 Store 。如下图,创建 Store 需要 reducer ,而 reducer 实际上是一个带有 stateaction 的方法,并返回新的 State 。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

所以我们需要先创建一个 State 对象 GSYState 类,用于储存需要共享的数据。比如下方代码的: 用户信息、主题、语言环境 等。

接着我们需要定义 Reducer 方法 appReducer :将 GSYState 内的每一个参数,和对应的 action 绑定起来,返回完整的 GSYState这样我们就确定了 State 和 Reducer 用于创建 Store

///全局Redux store 的对象,保存State数据
class GSYState {
///用户信息
User userInfo;

///主题
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([
///

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值