1. 程式人生 > 其它 >[Flutter] fish_redux是怎麼路由傳值的

[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}'),