flutter fish-redux的使用之-获取网络数据进阶使用

本文主要学习 fish-redux的 实战:

1、网络请求

2、切换主题,全局Store的使用

3、broadcast的使用

直接上动态效果

本文主要介绍网络请求使用

当我们请求网络数据时,其实跟我们在非fish-redux中请求网络差不多,在initState中请求,而fish-redux也提供了相应的api,如

Lifecycle.initState,还有其他api大家可以自行查看。

,如下代码所示:

Effect<IndexState> buildEffect() {
  return combineEffects(<Object, Effect<IndexState>>{
    Lifecycle.initState: _init,
  });
}


void _init(Action action, Context<IndexState> ctx) {
  requestGet(MUSIC_BROADCAST).then((data) {
    print(data);
    if (data != "") {
      List<ChannelTabBean> list = new List();
      for (int i = 0; i < data.length; i++) {
        var channelTabBean = ChannelTabBean.fromJson(data[i]);
        list.add(channelTabBean);
      }
      TickerProvider tickerProvider = ctx.stfState as TickerProvider;
      ctx.state.mController =
          new MyTabController(length: list.length, vsync: tickerProvider);
      ctx.dispatch(IndexActionCreator.updateTabList(list));
    }
  });
}

这里就是我请求网络数据的地方,requestGet方法这个是我自行封装的方法,当然这个请求框架是使用dio的,大家可根据需求自行封装。

这里代码有几个需要注意的地方是 TickerProvider tickerProvider = ctx.stfState as TickerProvider;这个地方是初始化TabController需要,这里还需要在page页配置一个IndexSingleTickerProviderState类对象如下所示:

class IndexPage extends Page<IndexState, Map<String, dynamic>> {
  IndexPage()
      : super(
          initState: initState,
          effect: buildEffect(),
          reducer: buildReducer(),
          view: buildView,
          wrapper: keepAliveWrapper,
          dependencies: Dependencies<IndexState>(
              adapter: null,
              slots: <String, Dependent<IndexState>>{
                'appBar': AppBarStateConnOp<IndexState, AppBarState>(
                        init: initAppBarState, key: 'appBar') +
                    AppBarComponent(),
              }),
          middleware: <Middleware<IndexState>>[],
        );

  @override
  ComponentState<IndexState> createState() {
    return IndexSingleTickerProviderState();
  }
}

其实这个类也没做啥就是实现了一个类如下所示:

class IndexSingleTickerProviderState extends ComponentState<IndexState>
    with SingleTickerProviderStateMixin {
}

还有一个就是获取数据后要更新数据,所以在action类中定义一个updateTabList的action。这里就不贴代码了,下面有源码地址。

这个地方ctx.dispatch(IndexActionCreator.updateTabList(list));就是将数据发送到reducer中更新数据,如下:

Reducer<IndexState> buildReducer() {
  return asReducer(
    <Object, Reducer<IndexState>>{
      IndexAction.updateTabList: _updateTabList,
    },
  );
}

IndexState _updateTabList(IndexState state, Action action) {
  final IndexState newState = state.clone()..tabList = action.payload;
  return newState;
}

ok,以上就是请求数据到更新数据整个流程。

传送门:demo

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值