初識Fish Redux在Flutter中使用

初識Fish Redux在Flutter中使用

本教程須要你在官方教程的基礎上有概念性的瞭解,若你對基礎概念不瞭解,請先閱讀官方介紹問文檔orGithub上的介紹。
Fluter應用框架Fish Redux官方介紹
Fish Redux Github地址git

開發工具:

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

基礎概念回顧:

官方推薦目錄樣式
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.dartgithub

關於Action

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

  • 構造方法 const Action(this.type, {this.payload}) {type 爲 枚舉類型的Action,payload爲傳遞dynamic類型數據}
//定義 Action Type
enum ItemAction { jumpDetail }
//ActionCreator定義方法
class ItemActionCreator {
  static Action onJumpDetail() {
    return const Action(ItemAction.jumpDetail);
  }
}
複製代碼

關於View

View顧名思義就是界面Widget展現,其 函數簽名:(T,Dispatch,ViewServices) => Widget 【T爲對應state.dart定義的數據,Dispatch能夠調用ActionCreator中方法,ViewService能夠調用建立Adapter或是Component】markdown

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()),
        ),

      ),
    ],
  );
}
複製代碼

關於Effect和Reducer

Effect和Reducer都屬於對Action事件操做行爲,這二者區別在於:Effect是對非數據操做行爲(包括State生命週期方法),Reducer是對數據操做行爲,簡單理解爲只要Reducer操做過原來數據就改變了。
Effect的函數簽名:(Context,Action) => Object
Reducer的函數簽名:(T,Action) => T網絡

///Effect 經常使用於定義 網絡數據請求,或是界面點擊事件等非數據操做
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經常使用語操做數據行爲,經過拿到Action payload中數據來對數據經過淺複製方式改變數據
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;
}
複製代碼

關於State

State爲定義Dart本地數據封裝類,其要實現Cloneable接口,當中數據改變經過淺複製方式,默認插件會實現initState方法框架

///下文Demo首頁列表數據
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();
}
複製代碼

關於Component

Component和Page相似都是對局部的展現和功能的封裝。
ide

三要素:
View(組件展現),Effect(非修改數據行爲),Reducer(修改數據行爲)函數

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(),
              }),

複製代碼

關於Connector

connector理解爲子數據與父數據綁定,在註冊component以及adapter使用
學習

兩種方式實現方式:

  • 實現 Reselect1 抽象類,主要用於對原有數據數據改造使用,好比原有數據列表數據有幾條等
///Demo 中須要統計 列表數據條數 講列表數與定義Component定義的state數據綁定在一塊兒
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) {}
}
複製代碼
  • 實現ConnOp類,用於Adapter數據綁定
///主要用於列表數據改變成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能夠實現數據集中化處理,分治解耦,帶來這些便利同時,也會帶來必定繁瑣行和易錯性,因此對於一些界面邏輯簡單,或是隻是列表展現不建議使用Fish Redux框架模式開發。
目前Fish Redux生命週期管理只限於State生命週期,基於mixins的WidgetsBindingObserver聲明週期方法,須要等待後期官方提供開放。

middleware層不是特別理解,有好的學習資料歡迎推薦學習,謝謝!!!

注:若有錯誤歡迎留言指正

相關文章
相關標籤/搜索