本文主要学习 fish-redux的 实战:
1、网络请求;
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