热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在Flutter使用Redux来共享状态和管理单一数据

React生态里广为人知的Redux状态管理,其实在Flutter中也能适用,它能很好的处理单一数据和状态共享,在一定程度上对于分割项目之间复杂的业务有一定的积极作用,可阅读可维护

React 生态里广为人知的 Redux 状态管理,其实在 Flutter 中也能适用,它能很好的处理单一数据和状态共享,在一定程度上对于分割项目之间复杂的业务有一定的积极作用,可阅读可维护也能做的很不错。对于使用过 React 的前端开发来说 Redux 的概念肯定熟记于心了,不过我还是要简单说一些东西,只有这样我们才能更好的进入下一个环节。

Redux 主要由三个部分组成:Store,Action,Reducer

  • Action 用于定义数据变化的行为(至少在语义上我们应该定义明确的行为)
  • Reducer 用于根据 Action 来产生新的状态
  • Store 用于存储和管理 state

《在 Flutter 使用 Redux 来共享状态和管理单一数据》
《在 Flutter 使用 Redux 来共享状态和管理单一数据》

这个项目的 Redux 例子使用了如下两个 package:

  • https://github.com/brianegan/flutter_redux
  • https://github.com/brianegan/flutter_redux_dev_tools

让我们先来看一看具体的效果图:

《在 Flutter 使用 Redux 来共享状态和管理单一数据》
《在 Flutter 使用 Redux 来共享状态和管理单一数据》

根据效果来分析我们的 Store 至少是一个数组,数组里面是一个对象,这个对象至少有两个属性分别是 name 和 icon,那么我们应该先来定义全局的 state 和 这个对象。

// 全局 state
class AppState {
List<AVList> data;
AppState(this.data);
}
import 'package:flutter/material.dart';
// 具体使用的对象 class AVList {
final String name;
final IconData icon;
AVList(this.name, this.icon);
AVList.fromJSON(Map<String, dynamic> json)
:name = json['name'],
icon = json['icon'];
}

你能看见它们分别做了两件事情,往ListView中添加一个Item,将最后一个Item从ListView中删除,那么接下来我们要定义它们的Action和Reducer。

// Action import 'package:my_flutter_app/flow/listModel.dart';
List<AVList> addItem(List<AVList> avLists, action){
avLists.add(action.avLists[0]);
return avLists;
}
List<AVList> removeItem(List<AVList> avLists, action){
avLists.removeLast();
return avLists;
}
import 'package:redux/redux.dart';
import 'package:my_flutter_app/flow/listModel.dart';
import 'package:my_flutter_app/flow/listActions.dart';
final ListReducer = combineReducers<List<AVList>>([
TypedReducer<List<AVList>, AddAVListAction>(addItem),
TypedReducer<List<AVList>, RemoveAVListAction>(removeItem)
]);
class AddAVListAction {
final List<AVList> avLists;
AddAVListAction(this.avLists);
}
class RemoveAVListAction {}

我们可以使用 combineReducers 来注册你的 Action,并且使用 TypedReducer 来映射你的 Action。

现在,我们可以在 main.dart 中定义你全局的 Store 和 Reducer :

AppState appReducer(AppState state, action) {
return new AppState(
ListReducer(state.data, action)
);
}
final store = new Store<AppState>(
appReducer,
initialState: new AppState([new AVList("android", Icons.android)])
);

之前我们定义的数据结构中是一个List,其中对象的类型是AVList,因为我们可以在初始化的时候给它一个默认值。

接下来我们可以来完善 Widget 这一层,在这一层中基本上我们需要做:

  • Widget 绑定 Store 中的 state
  • Widget 触发某个 Action
  • Reducer 根据某个 Action 触发更新 state
  • 更新 Store 中 state 绑定的 Widget

在这里我们会使用到几个 Widget 和一个 Dispatch 来完成上述的步骤,第一步我们要使用 StoreProvider 它会将绑定的 Store 传递给它的所有子 Widget ,其次我们需要使用 StoreConnector 它会将更新后的数据 callback 给你,最后我们会使用 dispatch 来执行某些 Action ,完成某些 state 的操作。

完整的例子:

import 'package:flutter/material.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:my_flutter_app/flow/listModel.dart';
import 'package:my_flutter_app/flow/listReducer.dart';
class AppState {
List<AVList> data;
AppState(this.data);
}
AppState appReducer(AppState state, action) {
return new AppState(
ListReducer(state.data, action)
);
}
class AVReduxList extends StatelessWidget {
final Store<AppState> store;
AVReduxList({
Key key,
this.store
}): super(key:key);
@override
Widget build(BuildContext context) {
return new StoreProvider<AppState>(
store: store,
child: new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('AVReduxList'),
),
body: new Column(
children: <Widget>[
new StoreConnector<AppState, List<AVList>>(
converter: (store) => store.state.data,
builder: (BuildContext context, data){
return new Container(
height: 500.0,
child: ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int position){
return new Padding(
padding: EdgeInsets.all(10.0),
child: new Row(
children: <Widget>[
new Text(data[position].name),
new Icon(data[position].icon, color: Colors.blue)
],
),
);
},
),
);
},
),
new Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new RaisedButton(
color: Colors.blue,
child: new Text(
'更新',
style: new TextStyle(
color: Colors.white
),
),
onPressed: (){
store.dispatch(new AddAVListAction(
[new AVList("android", Icons.android)]
));
},
),
new RaisedButton(
color: Colors.blue,
child: new Text(
'删除最后一项',
style: new TextStyle(
color: Colors.white
),
),
onPressed: (){
store.dispatch(
new RemoveAVListAction()
);
},
)
],
)
],
),
),
)
);
}
}

Redux Dev Tools

这是一个类似 Redux Time Travel 的 UI 小工具,在开发阶段我们可以使用这个工具来追溯你的操作,因此我们需要重新定义一个入口文件 main_dev.dart:

import 'package:flutter/material.dart';
import 'package:flutter_redux_dev_tools/flutter_redux_dev_tools.dart';
import 'package:redux_dev_tools/redux_dev_tools.dart';
import 'package:my_flutter_app/AVReduxList.dart';
import 'package:my_flutter_app/flow/listModel.dart';
void main(){
final store = new DevToolsStore<AppState>(
appReducer,
initialState: new AppState([new AVList("android", Icons.android)])
);
runApp(new ReduxDevToolsContainer(
store: store,
child: new AVReduxList(
store: store,
devDrawerBuilder: (BuildContext context){
return new Drawer(
child: new Padding(
padding: new EdgeInsets.only(top: 24.0),
child: new ReduxDevTools(store),
),
);
},
),
));
}

在这里我们需要使用 DevToolsStore 来定义你的全局 Store ,另外我们还需要对原来的 AVReduxList进行一些改造,增加一个 devDrawerBuilder 属性来控制 DevTools 的绘制。

// AVReduxList.dart
class AVReduxList extends StatelessWidget {
final Store<AppState> store;
final WidgetBuilder devDrawerBuilder;
AVReduxList({
Key key,
this.store,
this.devDrawerBuilder
}): super(key:key);
@override
Widget build(BuildContext context) {
return new StoreProvider<AppState>(
store: store,
child: new MaterialApp(
home: new Scaffold(
endDrawer: devDrawerBuilder != null ? devDrawerBuilder(context) : null,
...
)
)
)
}
}

最后,我们在 VSCode 中重新添加一个新的启动项:

{
"name": "Flutter_Redux_DevTools",
"type": "dart",
"request": "launch",
"program": "lib/main_dev.dart"
},

效果图:

《在 Flutter 使用 Redux 来共享状态和管理单一数据》
《在 Flutter 使用 Redux 来共享状态和管理单一数据》


推荐阅读
  • 先上图引入插件在pubspec.yaml中引入charts_flutter插件使用的时候版本到0.6.0,插件地址:https:github.comgooglecharts使用插件 ... [详细]
  • Go GUIlxn/walk 学习3.菜单栏和工具栏的具体实现
    本文介绍了使用Go语言的GUI库lxn/walk实现菜单栏和工具栏的具体方法,包括消息窗口的产生、文件放置动作响应和提示框的应用。部分代码来自上一篇博客和lxn/walk官方示例。文章提供了学习GUI开发的实际案例和代码示例。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 数组的排序:数组本身有Arrays类中的sort()方法,这里写几种常见的排序方法。(1)冒泡排序法publicstaticvoidmain(String[]args ... [详细]
  • (三)多表代码生成的实现方法
    本文介绍了一种实现多表代码生成的方法,使用了java代码和org.jeecg框架中的相关类和接口。通过设置主表配置,可以生成父子表的数据模型。 ... [详细]
  • flutter图片缓存Flutter的图片缓存机制有问题(可能是我使用的版本1.12.13有问题)网络图片会默认缓存到本地,但是不管图片是不是完整的或者损坏的,导致页面在下次进入的 ... [详细]
  • 篇首语:本文由编程笔记#小编为大家整理,主要介绍了Flutter添加APP启动StoryView相关的知识,希望对你有一定的参考价值。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 本文介绍了解决Netty拆包粘包问题的一种方法——使用特殊结束符。在通讯过程中,客户端和服务器协商定义一个特殊的分隔符号,只要没有发送分隔符号,就代表一条数据没有结束。文章还提供了服务端的示例代码。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
author-avatar
灬耗丨子灬
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有