这一节主要了解flutter-redux的用法,redux之前是用在React中的状态管理,一般较大型React项目用的较多,简单了解一下一些概念: (1)store:是保存数据的地方,整个应用只能有一个 Store ,Store 有十分重要的方法 dispatch(action) 来发送 Action。(2)State,是某个时间点的数据快照, 一个 State 对应一个 View,只要 State 相同,View 就相同。(3)Action:是 View 发出的通知,通过 Reducer 使 State 发生变化。(4)Reducer: 是一个纯函数,接受 Action 和当前 State 作为参数,返回一个新的 State,主要是做一些业务逻辑处理。(5)Middleware: 中间件,它的操作在发出 Action 和执行 Reducer 这两步之间发生,用于增加额外功能,如处理异步操作或者打印日志功能等。
flutter-redux是借鉴redux设计的。它里面涉及关键API如下: (1)StoreProvider:是一个InheritedWidget,用在应用的父布局,用来传递Store. (2)StoreConnector, 一个可以接收Store的Widget,响应Store发出的状态改变事件,然后重新渲染UI。它里面有两个关键参数 一个是converter,用来将store转化为ViewModel,另一个是builder,builder作用是将ViewModel转化为UI布局。看一个栗子:
-
pubspec.yaml:
-
redux:
">=5.0.0 <6.0.0"
-
flutter_redux: ^
0.8
.2
-
-
import
'package:flutter/material.dart';
-
import
'package:flutter_redux/flutter_redux.dart';
-
import
'package:redux/redux.dart';
-
-
enum Actions { Increment }
-
int counterReducer(int state, dynamic action) {
-
if (action == Actions.Increment) {
-
return state +
1;
-
}
-
return state;
-
}
-
-
void main() {
-
final store = Store<int>((int state,dynamic action) {
-
if(action == Actions.Increment) {
-
return state +
1;
-
}
-
return state;
-
},
initialState:
0);
-
-
runApp(
new MyApp(store: store));
-
}
-
-
class MyApp extends StatelessWidget {
-
final Store<int> store;
-
MyApp({Key key,
this.store}) :
super(key: key);
-
@override
-
Wid
get
build(
BuildContext context) {
-
//将 Redux Store传递给它的子Widget
-
return StoreProvider<int>(store: store,
-
child: MaterialApp(
-
home: MyHome(),
-
));
-
}
-
}
-
-
class MyHome extends StatefulWidget {
-
@override
-
_MyHomeState createState() => _MyHomeState();
-
}
-
-
class _MyHomeState extends State<MyHome> {
-
@override
-
Wid
get
build(
BuildContext context) {
-
return Scaffold(
-
appBar: AppBar(title: Text(
"Hello"),),
-
floatingActionButton: StoreConnector<int,VoidCallback>(
-
//将Action进行分发
-
converter:
(store) =>
() => store.dispatch(Actions.Increment),
-
builder:
(context,cb) => FloatingActionButton(
-
onPressed: cb,
-
child: Icon(Icons.add),
-
),
-
),
-
body: Column(
-
mainAxisAlignment: MainAxisAlignment.center,
-
children: <Widget>[
-
//能够接收store
-
StoreConnector<int,String>(
-
converter: (store) => store.state.toString(),
-
builder: (context,count) {
-
return Center(child: Text('$count'),);
-
},
-
)
-
],
-
),
-
);
-
}
-
}
转载:https://blog.csdn.net/ljt2724960661/article/details/116307211