初識Fish Redux在Flutter中使用

初識Fish Redux在Flutter中使用

本教程需要你在官方教程的基礎(chǔ)上有概念性的了解,若你對基礎(chǔ)概念不了解,請先閱讀官方介紹問文檔orGithub上的介紹。

Fluter應用框架Fish Redux官方介紹

Fish Redux Github地址

開發(fā)工具:

  • Android Studio
  • FishReduxTemplate(AS中插件,方便快速搭建Fish Redux)

基礎(chǔ)概念回顧:

官方推薦目錄樣式

sample_page
-- action.dart
-- page.dart
-- view.dart
-- effect.dart
-- reducer.dart
-- state.dart
components
sample_component
-- action.dart
-- component.dart
-- view.dart
-- effect.dart
-- reducer.dart
-- state.dart

關(guān)于Action

Action我把它理解為事件類型聲明的聲明,先是枚舉定義Action type,在對應Action Creator中定義事件方法,方便dispatch調(diào)用對應Action事件。

  • 構(gòu)造方法 const Action(this.type, {this.payload}) {type 為 枚舉類型的Action,payload為傳遞dynamic類型數(shù)據(jù)}
//定義 Action Type
enum ItemAction { jumpDetail }
//ActionCreator定義方法
class ItemActionCreator {
  static Action onJumpDetail() {
    return const Action(ItemAction.jumpDetail);
  }
}

關(guān)于View

View顧名思義就是界面Widget展示,其
函數(shù)簽名:(T,Dispatch,ViewServices) => Widget 【T為對應state.dart定義的數(shù)據(jù),Dispatch可以調(diào)用ActionCreator中方法,ViewService可以調(diào)用創(chuàng)建Adapter或是Component】

Widget buildView(ItemState state, Dispatch dispatch, ViewService viewService) {
  return Column(
    children: <Widget>[
      Container(
        padding: const EdgeInsets.all(10),
        child: GestureDetector(
          child:  Row(......),
          onTap: ()=> dispatch(ItemActionCreator.onJumpDetail()),
        ),

      ),
    ],
  );
}

關(guān)于Effect和Reducer

Effect和Reducer都屬于對Action事件操作行為,這兩者區(qū)別在于:Effect是對非數(shù)據(jù)操作行為(包括State<StatefulWidget>生命周期方法),Reducer是對數(shù)據(jù)操作行為,簡單理解為只要Reducer操作過原來數(shù)據(jù)就改變了。

Effect的函數(shù)簽名:(Context,Action) => Object

Reducer的函數(shù)簽名:(T,Action) => T

///Effect 常用于定義 網(wǎng)絡數(shù)據(jù)請求,或是界面點擊事件等非數(shù)據(jù)操作
Effect<ItemState> buildEffect() {
  return combineEffects(<Object, Effect<ItemState>>{
    ItemAction.jumpDetail: _onJumpDetail,
  });
}
void _onJumpDetail(Action action, Context<ItemState> ctx) {
  Navigator.push(ctx.context, MaterialPageRoute(builder: (buildContext) {
    return DetailPage().buildPage({'item': ctx.state});
  }));
}

//Reducer常用語操作數(shù)據(jù)行為,通過拿到Action payload中數(shù)據(jù)來對數(shù)據(jù)通過淺復制方式改變數(shù)據(jù)
Reducer<DetailState> buildReducer() {
  return asReducer(
    <Object, Reducer<DetailState>>{
      DetailAction.loadDone: _onLoadDone,
      ......
    },
  );
}

DetailState _onLoadDone(DetailState state, Action action) {
  final List<String> list = action.payload ?? <String>[];
  final DetailState newState = state.clone();
  newState.list = list;
  return newState;
}

關(guān)于State

State為定義Dart本地數(shù)據(jù)封裝類,其要實現(xiàn)Cloneable接口,當中數(shù)據(jù)改變通過淺復制方式,默認插件會實現(xiàn)initState方法

///下文Demo首頁列表數(shù)據(jù)
class ItemState implements Cloneable<ItemState> {
  String title;
  String subTitle;

  ItemState({this.title, this.subTitle});

  @override
  ItemState clone() {
    return ItemState()
      ..title = title
      ..subTitle = subTitle;
  }
}

ItemState initState(Map<String, dynamic> args) {
  return ItemState();
}

關(guān)于Component

Component和Page類似都是對局部的展示和功能的封裝。

三要素:

View(組件展示),Effect(非修改數(shù)據(jù)行為),Reducer(修改數(shù)據(jù)行為)

component使用通常用viewService.buildComponent('component name')

class ItemComponent extends Component<ItemState> {
  ItemComponent()
      : super(
            effect: buildEffect(),
            reducer: buildReducer(),
            view: buildView,
            dependencies: Dependencies<ItemState>(
                adapter: null,
                slots: <String, Dependent<ItemState>>{
                }),);
}

///需要Page界面注冊 Component
 dependencies: Dependencies<HomeState>(
              adapter: ItemAdapter(),
              slots: <String, Dependent<HomeState>>{
                'header': HeaderConnector() + HeaderComponent(),
              }),

關(guān)于Connector

connector理解為子數(shù)據(jù)與父數(shù)據(jù)綁定,在注冊component以及adapter使用

兩種方式實現(xiàn)方式:

  • 實現(xiàn) Reselect1 抽象類,主要用于對原有數(shù)據(jù)數(shù)據(jù)改造使用,比如原有數(shù)據(jù)列表數(shù)據(jù)有幾條等
///Demo 中需要統(tǒng)計 列表數(shù)據(jù)條數(shù) 講列表數(shù)與定義Component定義的state數(shù)據(jù)綁定在一起
class HeaderConnector extends Reselect1<HomeState, HeaderState, int> {
  @override
  HeaderState computed(int state) {
    return HeaderState()..total = state;
  }

  @override
  int getSub0(HomeState state) {
    return state.list.length;
  }

  @override
  void set(HomeState state, HeaderState subState) {}
}
  • 實現(xiàn)ConnOp類,用于Adapter數(shù)據(jù)綁定
///主要用于列表數(shù)據(jù)改變成ItemBean,提供set,get方法
class _ItemConnector extends ConnOp<HomeState, List<ItemBean>> {
  @override
  List<ItemBean> get(HomeState state) {
    if (state.list.isNotEmpty) {
      return state.list
          .map((itemState) => ItemBean('item', itemState))
          .toList();
    } else {
      return <ItemBean>[];
    }
  }

  @override
  void set(HomeState state, List<ItemBean> items) {
    if (items.isNotEmpty) {
      state.list = List<ItemState>.from(
          items.map((ItemBean bean) => bean.data).toList());
    } else {
      state.list = <ItemState>[];
    }
  }

  @override
  subReducer(reducer) {
    // TODO: implement subReducer
    return super.subReducer(reducer);
  }
}

Demo源碼地址

使用場景

Fish Redux可以實現(xiàn)數(shù)據(jù)集中化處理,分治解耦,帶來這些便利同時,也會帶來一定繁瑣行和易錯性,所以對于一些界面邏輯簡單,或是只是列表展示不建議使用Fish Redux框架模式開發(fā)。

目前Fish Redux生命周期管理只限于State<StatefulWidget>生命周期,基于mixins的WidgetsBindingObserver聲明周期方法,需要等待后期官方提供開放。

<font color=red>middleware層不是特別理解,有好的學習資料歡迎推薦學習,謝謝!!!</font>

<font color=red>注:如有錯誤歡迎留言指正</font>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容