title: flutter_redux
date: 2019-11-03 20:48:18
tags:
- flutter
flutter_redux的入門級使用
反正安裝最新依賴就OK了
dependencies:
flutter_redux: ^0.5.3
Redux
注意:你也可以把這些state actions reducer 切割開毅否,它和react-redux一樣的
//reducer 核心代碼
// int state = 0;
// 開始這里是一個數(shù)字
// 如果他是一個對象怎么樣
// 單向閉環(huán)
//count 狀態(tài)
class CountState {
int _count = 0;
get count => _count;
String _username = '';
get username => _username ;
//狀態(tài)初始化
CountState.initState() {
this._count = 0;
this._username = '';
}
//state構(gòu)造函數(shù)
CountState(this._count,this._username);
}
//枚舉actions
enum AllActions { Increment, SetUserName }
//reducer
CountState counterReducer(CountState state, dynamic action) {
// reducer 是一個純函數(shù)
//store.dispatch() 傳入了一個數(shù)組
// 第一個參數(shù)是actionstype
var actionsType = action[0];
//第二個參數(shù)是要更改的新數(shù)據(jù)
var actionArgments = action[1];
//分支選擇
switch (actionsType) {
case AllActions.Increment:
//修改狀態(tài)返回新的狀態(tài)去覆蓋原來的狀態(tài)
state._count += 100;
state._username = actionArgments;
return state;
}
return state;
}
Widget代碼部分
floatingActionButton: new StoreConnector<CountState, VoidCallback>(
//converter轉(zhuǎn)換器 在轉(zhuǎn)換器里面調(diào)用actions
converter: (store) {
return () => store.dispatch([AllActions.Increment,'張三']);
//傳值和通知reducer
},
//構(gòu)造按鈕
builder: (context, callback) {
return new FloatingActionButton(
onPressed: callback,
//這里的callback就是上面的轉(zhuǎn)換器
///你也可以這樣寫
///onPressed:(){
/// callback();
/// //TODO
///}
tooltip: 'Increment',
child: new Icon(Icons.add),
);
},
),
讀取store里面狀態(tài)
StoreConnector<CountState, String>(
converter: (store) => store.state.count.toString(),
builder: (context, count) {
//設(shè)置count
return Text(count);
},
),
StoreConnector<CountState, String>(
converter: (store) => store.state.username.toString(),
builder: (context, username) {
//設(shè)置username
return Text(username);
},
),
你需要在main函數(shù)里面?zhèn)鬟fStore
void main () {
final store = new Store<CountState>(counterReducer, initialState: CountState.initState());
runApp(new MyApp(
title: 'Flutter Redux Demo',
store: store,
));
}