Skip to content

Commit

Permalink
优化Future类型请求处理
Browse files Browse the repository at this point in the history
  • Loading branch information
simplezhli committed Jul 15, 2019
1 parent a620388 commit e5fa85d
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 90 deletions.
12 changes: 5 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,6 @@ iOS需要自行下载代码运行。(效果是一致的)

* [ ] 引入状态管理,预计使用 [provider](https://github.com/rrousselGit/provider)


## 友情赞助

对Flutter有兴趣的可以通过下图的二维码购买陈航老师的课程。

<img src="preview/jikeshijian.jpg" width="450px"/>

## TODO

已知问题:
Expand All @@ -145,6 +138,11 @@ iOS需要自行下载代码运行。(效果是一致的)

- [Flutter-TianYue](https://github.com/ZDfordream/Flutter-TianYue)

## 友情赞助

对Flutter有兴趣的可以通过下图的二维码购买陈航老师的课程。

<img src="preview/jikeshijian.jpg" width="450px"/>

## License

Expand Down
55 changes: 16 additions & 39 deletions lib/mvp/base_page_presenter.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

import 'package:dio/dio.dart';
import 'package:flutter_deer/net/base_entity.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:meta/meta.dart';

import 'mvps.dart';

Expand Down Expand Up @@ -36,54 +36,34 @@ class BasePagePresenter<V extends IMvpView> extends IPresenter {
void initState() {}

/// 返回Future 适用于刷新,加载更多
Future request<T>(Method method, String url, {bool isShow : true, bool isClose: true, Function(T t) onSuccess, Function(int code, String mag) onError, Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
Future request<T>(Method method, {@required String url, bool isShow : true, bool isClose: true, Function(T t) onSuccess, Function(int code, String mag) onError, Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
if (isShow) view.showProgress();
await DioUtils.instance.request<T>(method, url,
params: params,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken?? _cancelToken
).then((BaseEntity<T> result){
if (result.code == 0){
if (onSuccess != null){
onSuccess(result.data);
}
}else{
if (result.message.isNotEmpty){
view.showToast(result.message);
}
if (onError != null){
onError(result.code, result.message);
}
}
});
options: options,
cancelToken: cancelToken?? _cancelToken,
onSuccess: onSuccess,
onError: onError
);
if (isClose) view.closeProgress();
}

/// 返回Future 适用于刷新,加载更多
Future requestList<T>(Method method, String url, {bool isShow : true, bool isClose: true, Function(List<T> t) onSuccess, Function(int code, String mag) onError, Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
Future requestList<T>(Method method, {@required String url, bool isShow : true, bool isClose: true, Function(List<T> t) onSuccess, Function(int code, String mag) onError, Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
if (isShow) view.showProgress();
await DioUtils.instance.requestList<T>(method, url,
params: params,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken?? _cancelToken
).then((BaseEntity<List<T>> result){
if (result.code == 0){
onSuccess(result.data);
}else{
if (result.message.isNotEmpty){
view.showToast(result.message);
}
if (onError != null){
onError(result.code, result.message);
}
}
});
params: params,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken?? _cancelToken,
onSuccess: onSuccess,
onError: onError
);
if (isClose) view.closeProgress();
}

void requestNetwork<T>(Method method, String url, {bool isShow : true, bool isClose: true, Function(T t) onSuccess, Function(List<T> list) onSuccessList, Function(int code, String mag) onError,
void requestNetwork<T>(Method method, {@required String url, bool isShow : true, bool isClose: true, Function(T t) onSuccess, Function(List<T> list) onSuccessList, Function(int code, String mag) onError,
Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options, bool isList : false}){
if (isShow) view.showProgress();
DioUtils.instance.requestNetwork<T>(method, url,
Expand All @@ -106,9 +86,6 @@ class BasePagePresenter<V extends IMvpView> extends IPresenter {
},
onError: (code, msg){
if (isClose) view.closeProgress();
if (msg.isNotEmpty){
view.showToast(msg);
}
if (onError != null) {
onError(code, msg);
}
Expand Down
80 changes: 55 additions & 25 deletions lib/net/dio_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -103,30 +103,46 @@ class DioUtils {
return options;
}

Future<BaseEntity<T>> request<T>(Method method, String url, {Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
try{
String m = _getRequestMethod(method);
return await _request<T>(m, url, data: params, queryParameters: queryParameters, options: options, cancelToken: cancelToken);
}catch(e){
if (e is DioError && CancelToken.isCancel(e)){
Log.i("取消请求接口: $url");
Future request<T>(Method method, String url, {Function(T t) onSuccess, Function(int code, String mag) onError, Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
String m = _getRequestMethod(method);
return await _request<T>(m, url,
data: params,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken).then((BaseEntity<T> result){
if (result.code == 0){
if (onSuccess != null){
onSuccess(result.data);
}
}else{
onError == null ? _onError(result.code, result.message) : onError(result.code, result.message);
}
}, onError: (e, _){
_cancelLogPrint(e, url);
Error error = ExceptionHandle.handleException(e);
return Future.value(BaseEntity(error.code, error.msg, null));
}
onError == null ? _onError(error.code, error.msg) : onError(error.code, error.msg);
});
}

Future<BaseEntity<List<T>>> requestList<T>(Method method, String url, {Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
try{
String m = _getRequestMethod(method);
return await _requestList<T>(m, url, data: params, queryParameters: queryParameters, options: options, cancelToken: cancelToken);
}catch(e){
if (e is DioError && CancelToken.isCancel(e)){
Log.i("取消请求接口: $url");
Future requestList<T>(Method method, String url, {Function(List<T> t) onSuccess, Function(int code, String mag) onError, Map<String, dynamic> params, Map<String, dynamic> queryParameters, CancelToken cancelToken, Options options}) async {
String m = _getRequestMethod(method);
return await _requestList<T>(m, url,
data: params,
queryParameters: queryParameters,
options: options,
cancelToken: cancelToken).then((BaseEntity<List<T>> result){
if (result.code == 0){
if (onSuccess != null){
onSuccess(result.data);
}
}else{
onError == null ? _onError(result.code, result.message) : onError(result.code, result.message);
}
}, onError: (e, _){
_cancelLogPrint(e, url);
Error error = ExceptionHandle.handleException(e);
return Future.value(BaseEntity(error.code, error.msg, []));
}
onError == null ? _onError(error.code, error.msg) : onError(error.code, error.msg);
});
}

/// 统一处理(onSuccess返回T对象,onSuccessList返回List<T>)
Expand All @@ -138,22 +154,36 @@ class DioUtils {
.asBroadcastStream()
.listen((result){
if (result.code == 0){
isList ? onSuccessList(result.data) : onSuccess(result.data);
if (isList){
if (onSuccessList != null){
onSuccessList(result.data);
}
}else{
if (onSuccess != null){
onSuccess(result.data);
}
}
}else{
onError == null ? _onError(result.code, result.message) : onError(result.code, result.message);
}
}, onError: (e){
if (e is DioError && CancelToken.isCancel(e)){
Log.i("取消请求接口: $url");
}
_cancelLogPrint(e, url);
Error error = ExceptionHandle.handleException(e);
onError == null ? _onError(error.code, error.msg) : onError(error.code, error.msg);
});
}

_onError(int code, String mag){
Log.e("接口请求异常: code: $code, mag: $mag");
Toast.show(mag);
_cancelLogPrint(dynamic e, String url){
if (e is DioError && CancelToken.isCancel(e)){
Log.i("取消请求接口: $url");
}
}

_onError(int code, String msg){
Log.e("接口请求异常: code: $code, mag: $msg");
if (code != ExceptionHandle.cancel_error){
Toast.show(msg);
}
}

String _getRequestMethod(Method method){
Expand Down
2 changes: 1 addition & 1 deletion lib/net/error_handle.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class ExceptionHandle {
error.type == DioErrorType.RECEIVE_TIMEOUT){
return Error(timeout_error, "连接超时!");
}else if (error.type == DioErrorType.CANCEL){
return Error(cancel_error, "");
return Error(cancel_error, "取消请求");
}else{
return Error(unknown_error, "未知异常");
}
Expand Down
3 changes: 2 additions & 1 deletion lib/shop/presenter/shop_presenter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ class ShopPagePresenter extends BasePagePresenter<ShopState> {
WidgetsBinding.instance.addPostFrameCallback((_){
/// 接口请求例子
/// get请求参数queryParameters post请求参数params
requestNetwork<UserEntity>(Method.get, "users/simplezhli",
requestNetwork<UserEntity>(Method.get,
url: "users/simplezhli",
onSuccess: (data){
view.setImg(data.avatarUrl);
},
Expand Down
17 changes: 10 additions & 7 deletions lib/util/log_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,45 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'package:common_utils/common_utils.dart';

class Log{

static const perform = const MethodChannel("x_log");

static d(String msg, {tag: 'X-LOG'}) {
perform.invokeMethod('logD', {'tag': tag, 'msg': msg});
_print(msg);
_print(msg, tag: tag);
}

static w(String msg, {tag: 'X-LOG'}) {
perform.invokeMethod('logW', {'tag': tag, 'msg': msg});
_print(msg);
_print(msg, tag: tag);
}

static i(String msg, {tag: 'X-LOG'}) {
perform.invokeMethod('logI', {'tag': tag, 'msg': msg});
_print(msg);
_print(msg, tag: tag);
}

static e(String msg, {tag: 'X-LOG'}) {
perform.invokeMethod('logE', {'tag': tag, 'msg': msg});
_print(msg);
_print(msg, tag: tag);
}

static json(String msg, {tag: 'X-LOG'}) {
try {
perform.invokeMethod('logJson', {'tag': tag, 'msg': msg});
_print(msg);
_print(msg, tag: tag);
} catch (e) {
d(msg);
}
}

static _print(String msg){
static _print(String msg, {tag: 'X-LOG'}){
if (defaultTargetPlatform == TargetPlatform.iOS){
debugPrint(msg);
LogUtil.debuggable = true;
LogUtil.v(msg, tag: tag);
}
}
}
12 changes: 6 additions & 6 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ packages:
name: common_utils
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.1"
version: "1.1.3"
convert:
dependency: transitive
description:
Expand Down Expand Up @@ -98,7 +98,7 @@ packages:
name: dio
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.10"
version: "2.1.13"
flukit:
dependency: "direct main"
description:
Expand Down Expand Up @@ -130,7 +130,7 @@ packages:
description:
path: "."
ref: HEAD
resolved-ref: d717b5c5958b583e44e8e2144b3693e969585775
resolved-ref: "136e0c2da1a00dc9180a0d452e593ac89d47b3e8"
url: "git://github.com/simplezhli/flutter_2d_amap.git"
source: git
version: "0.0.1"
Expand Down Expand Up @@ -250,14 +250,14 @@ packages:
name: rxdart
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.21.0"
version: "0.22.0"
shared_preferences:
dependency: transitive
description:
name: shared_preferences
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.5.3+1"
version: "0.5.3+2"
simple_gesture_detector:
dependency: "direct main"
description:
Expand Down Expand Up @@ -374,7 +374,7 @@ packages:
name: webview_flutter
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.3.9+1"
version: "0.3.10"
sdks:
dart: ">=2.3.0-dev.0.5.flutter-a1668566e5 <3.0.0"
flutter: ">=1.5.0 <2.0.0"
8 changes: 4 additions & 4 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ dependencies:
# Toast插件 https://github.com/OpenFlutter/flutter_oktoast
oktoast: ^2.2.0
# 网络库 https://github.com/flutterchina/dio
dio: ^2.1.10
dio: ^2.1.13
# https://github.com/ReactiveX/rxdart
rxdart: ^0.21.0
rxdart: ^0.22.0
# Dart 常用工具类库 https://github.com/Sky24n/common_utils
common_utils: ^1.1.1
common_utils: ^1.1.3
# Flutter 常用工具类库 https://github.com/Sky24n/flustars
flustars: 0.2.5
# Flutter UI组件库 https://github.com/flutterchina/flukit.
Expand All @@ -45,7 +45,7 @@ dependencies:
# 侧滑删除 https://github.com/letsar/flutter_slidable
flutter_slidable: ^0.5.3
# WebView插件 https://github.com/flutter/plugins/tree/master/packages/webview_flutter
webview_flutter: 0.3.9+1
webview_flutter: 0.3.10
# 处理键盘事件 https://github.com/diegoveloper/flutter_keyboard_actions
keyboard_actions: ^2.1.1+1
# 列表悬浮头 https://github.com/fluttercommunity/flutter_sticky_headers
Expand Down

0 comments on commit e5fa85d

Please sign in to comment.