正常我們使用dio處理網(wǎng)絡(luò)請求時,都是放在init方法中進行實現(xiàn),那么在fish_redux中如何拿到init方法呢,其實無論是在effect或者reducer中我們都可以通過注冊監(jiān)聽對象Lifecycle.initState拿到對應(yīng)的init回調(diào),不過筆者認為,對于reducer應(yīng)該是處理state相關(guān)的數(shù)據(jù),相反的effect處理非state事件,因此在effect 中注冊對應(yīng)方法,處理網(wǎng)絡(luò)請求
實現(xiàn)效果

Untitled4.gif
代碼示例如下
- service網(wǎng)絡(luò)請求
class Service {
static Dio dio = Dio(BaseOptions(
connectTimeout: 30000,
receiveTimeout: 30000,
baseUrl: API.base_url,
contentType: ContentType.parse(
"application/x-www-form-urlencoded; charset=utf-8")));
static Future<T> post<T>(
String path, {
data,
Map<String, dynamic> queryParameters,
Options options,
CancelToken cancelToken,
ProgressCallback onSendProgress,
ProgressCallback onReceiveProgress,
}) {
return dio
.post<T>(path,
queryParameters: queryParameters,
options: options,
data: data,
cancelToken: cancelToken,
onSendProgress: onSendProgress,
onReceiveProgress: onReceiveProgress)
.then((value) => value.data);
}
}
class ServiceHepher {
static Future<ExampleModel> getExampleList() =>
Service.post(API.home_list).then((json) => ExampleModel.fromJson(json));
}
- effect 網(wǎng)絡(luò)請求處理
Effect<DioTestState> buildEffect() {
return combineEffects(<Object, Effect<DioTestState>>{
DioTestAction.action: _onAction,
DioTestAction.onOpenWeb: _onOpenWeb,
Lifecycle.initState: _init,
});
}
void _onAction(Action action, Context<DioTestState> ctx) {}
void _onOpenWeb(Action action, Context<DioTestState> ctx) {
final Items item = action.payload;
Routers.openWeb(ctx.context, item.url, item.title);
}
void _init(Action action, Context<DioTestState> ctx) {
//為封裝好的post請求,發(fā)送信號為didFeatch
ServiceHepher.getExampleList().then(
(value) => ctx.dispatch(DioTestActionCreator.didFeatchAction(value)));
}
- reducer 刷新state
Reducer<DioTestState> buildReducer() {
return asReducer(
<Object, Reducer<DioTestState>>{
DioTestAction.action: _onAction,
DioTestAction.didFeatch: _didFeatchAction,
},
);
}
DioTestState _onAction(DioTestState state, Action action) {
final DioTestState newState = state.clone();
return newState;
}
//接收信號為didFeatch
DioTestState _didFeatchAction(DioTestState state, Action action) {
final ExampleModel model = action.payload;
final DioTestState newState = state.clone();
newState.beans = model.data;
return newState;
}
擴展一下代碼中使用的webview控件
使用方法示例
class WebPage extends StatefulWidget {
final String webUrl;
final String webTitle;
WebPage({this.webUrl, this.webTitle});
@override
_WebPageState createState() => _WebPageState();
}
class _WebPageState extends State<WebPage> {
@override
Widget build(BuildContext context) {
return WebviewScaffold(
url: widget.webUrl,
appBar: AppBar(
title: Text(widget.webTitle),
),
);
}
}
- 例子只是展示web作用,傳入對應(yīng)url即可