[Flutter] fish_redux是怎么路由传值的
fish_redux是怎么相互传值的
声明:
本文只说明fish_redux里的路由传参,以及两个页面是怎么得到对方传过来的参数的。
对于demo的计数加1并刷新页面的方法我在另一篇文章有写过,所以本文不会说。
路由传值demo可看这里示例demo
下文的CountPage = FirstPage,DetailPage = SecondPage
基本流程图
01: FirstPage to SecondPage
STEP01 FirstPage view
///调度一个跳转到第二个页面的方法
onPressed: () {
dispatch(CountActionCreator.toDetail());
},
STEP02 FirstPage action
///接收view传来的意图,建立方法
static Action toDetail() {
return Action(CountAction.toDetail);
}
STEP03 FirstPage effect
///建立完方法,通知effect,处理跳转操作
void _toDetail(Action action, Context<CountState> ctx) async {
///路由带参数跳转到第二页面
var result = await Navigator.of(ctx.context)
.pushNamed("DetailPage", arguments: {"count": ctx.state.count});
///下面的操作是SecondPage to FirstPage做的提前操作,就是拿路由的返回值。
ctx.dispatch(CountActionCreator.updateCount((result as Map)["count"]));
}
STEP04 SecondPage state
///在第二个页面的state的initState里初始化传过来的值
DetailState initState(Map<String, dynamic> args) {
return DetailState()..count = args['count'];
}
STEP05 SecondPage view
///显示当前state的count
Text('${state.count}'),
02: SecondPage to FirstPage
STEP01 SecondPage view
///dispatch一个返回的方法
onPressed: () {
dispatch(DetailActionCreator.backFirst());
},
STEP02 SecondPage action
///建立返回的方法
static Action backFirst() {
return const Action(DetailAction.backFirst);
}
STEP03 SecondPage effect
///为建立方法执行pop并传参数回去
void _backFirst(Action action, Context<DetailState> ctx) {
Navigator.pop(ctx.context, {"count": ctx.state.count});
}
STEP04 FirstPage effect
///在toDetail方法里接收到SecondPage返回的值,并通过dispatch通知action建立更新的方法
void _toDetail(Action action, Context<CountState> ctx) async {
///路由带参数跳转到第二页面
var result = await Navigator.of(ctx.context)
.pushNamed("DetailPage", arguments: {"count": ctx.state.count});
///上面路由跳转的返回值是Future,打开传给result,注意此处的返回值是第二个页面传过来的参数
///拿到result里面的count参数,并且调度action建立更新的方法updateCount
ctx.dispatch(CountActionCreator.updateCount((result as Map)["count"]));
}
STEP05 FirstPage action
///action建立更新的方法并通知reducer更新数据
static Action updateCount(int count) {
return Action(CountAction.updateCount, payload: count);
}
STEP06 FirstPage reducer
///clone state并且将返回的参数赋值给新的state的count,并刷新
CountState _updateCount(CountState state, Action action) {
final CountState newState = state.clone();
newState..count=action.payload;
return newState;
}
STEP07 FirstPage view
///显示当前state的count(即从第二个页面过来的count
Text('${state.count}'),
分类:
Flutter学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】