本分主要介绍闲鱼出品的fish redux基础知识和使用,后续会有复杂应用场景分享。
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('$_counter'),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
flutter的计数demo,方便后面对比。
简单说就是用户操作dispatcher(action),到reducer中处理相关数据和逻辑,存储数据到store中,更新state,触发UI刷新。
部分重要概念
enum MessageAction {
onShare,
shared,
}
class MessageActionCreator {
static Action onShare(Map payload) {
return Action(MessageAction.onShare, payload: payload);
}
static Action shared() {
return const Action(MessageAction.shared);
}
}
Reducer buildMessageReducer() {
return asReducer(
基础目录
> -action.dart
> -effect.dart(本例中非必须)
> -page.dart
> -reducer.dart
> -state.dart
> -view.dart
action.dart
enum CounterAction { add, onAdd }
class CounterActionCreator {
//reducer使用
static Action add() {
return const Action(CounterAction.add);
}
//effect使用
static Action onAdd() {
return const Action(CounterAction.onAdd);
}
}
state.dart
class CounterState implements Cloneable {
int count = 0;
@override
CounterState clone() {
return CounterState()..count = count;
}
}
CounterState initState(Map args){
//什么也没做,只是初始化数据
return CounterState();
}
reducer.dart
Reducer buildReducer() {
return asReducer(
effect.dart
Effect buildEffect() {
return combineEffects(
view.dart
Widget buildView(
CounterState state, Dispatch dispatch, ViewService viewService) {
return Scaffold(
appBar: AppBar(
title: Text('CounterFishRedux'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
state.count.toString(),
)
],
),
),
floatingActionButton: FloatingActionButton(
//发送的action到了Effect中处理
onPressed: () => dispatch(CounterActionCreator.onAdd()),
//也可以发action到reducer中处理
//onPressed: () => dispatch(CounterActionCreator.add()),
tooltip: 'add',
child: Icon(Icons.add),
),
);
}
page.dart
class CounterFishReduxPage extends Page> {
CounterFishReduxPage()
: super(
initState: initState,
effect: buildEffect(),
reducer: buildReducer(),
view: buildView,
);
}
在view.dart中,用户触发FloatingActionButton的onPress事件,dispatch了名为onAdd的Action,在effect.dart中接收到action,会继续dispatch,到reducer.dart中(这一步非必须,可以直接dispatch到reducer.dart中),在reducer.dart中,在state中取出state中的数据,处理(加一)后,返回state,数据更新到store中,触发UI更新,最终到view.dart中state中的数据会更新,取出新的数据显示。
fish redux适用于中大型项目,这种简单的功能直接用官方的setState
即可。
这样就可以单独作为一个page或者component使用,没有逻辑和UI的耦合。