Flutter完整的Dio网络框架null空安全二次封装。
admin
2024-01-25 10:47:28
0
所需依赖添加在项目中的pubspec.yaml中:
dio: ^4.0.6                                       #网络请求
connectivity_plus: ^2.3.6                         #网络监测
pretty_dio_logger: ^1.1.1                         #日志打印
class HttpRequest {// 单例模式使用Http类,static final HttpRequest _instance = HttpRequest._internal();factory HttpRequest() => _instance;static late final Dio dio;/// 内部构造方法HttpRequest._internal() {/// 初始化dioBaseOptions options = BaseOptions(connectTimeout: HttpOptions.connectTimeout,receiveTimeout: HttpOptions.receiveTimeout,sendTimeout: HttpOptions.sendTimeout,baseUrl: HttpOptions.baseUrl);dio = Dio(options);/// 添加各种拦截器dio.interceptors.add(ErrorInterceptor());dio.interceptors.add(PrettyDioLogger(requestHeader: true,requestBody: true,responseHeader: true,responseBody: true));}/// 封装request方法Future request({required String path,required HttpMethod method,dynamic data,Map? queryParameters,bool showLoading = true,bool showErrorMessage = true,}) async {const Map methodValues = {HttpMethod.get: 'get',HttpMethod.post: 'post',HttpMethod.put: 'put',HttpMethod.delete: 'delete',HttpMethod.patch: 'patch',HttpMethod.head: 'head'};//动态添加header头Map headers = Map();headers["version"] = "1.0.0";Options options = Options(method: methodValues[method],headers: headers,);try {if (showLoading) {EasyLoading.show(status: 'loading...');}Response response = await HttpRequest.dio.request(path,data: data,queryParameters: queryParameters,options: options,);return response.data;} on DioError catch (error) {HttpException httpException = error.error;if (showErrorMessage) {EasyLoading.showToast(httpException.msg);}} finally {if (showLoading) {EasyLoading.dismiss();}}}
}enum HttpMethod {get,post,delete,put,patch,head,
}

class ErrorInterceptor extends Interceptor {@overridevoid onError(DioError err, ErrorInterceptorHandler handler) async {/// 根据DioError创建HttpExceptionHttpException httpException = HttpException.create(err);/// dio默认的错误实例,如果是没有网络,只能得到一个未知错误,无法精准的得知是否是无网络的情况/// 这里对于断网的情况,给一个特殊的code和msgif (err.type == DioErrorType.other) {var connectivityResult = await (Connectivity().checkConnectivity());if (connectivityResult == ConnectivityResult.none) {httpException = HttpException(code: -100, msg: 'None Network.');}}/// 将自定义的HttpExceptionerr.error = httpException;/// 调用父类,回到dio框架super.onError(err, handler);}
}

class HttpException implements Exception {final int code;final String msg;HttpException({this.code = -1,this.msg = 'unknow error',});@overrideString toString() {return 'Http Error [$code]: $msg';}factory HttpException.create(DioError error) {/// dio异常switch (error.type) {case DioErrorType.cancel:{return HttpException(code: -1, msg: 'request cancel');}case DioErrorType.connectTimeout:{return HttpException(code: -1, msg: 'connect timeout');}case DioErrorType.sendTimeout:{return HttpException(code: -1, msg: 'send timeout');}case DioErrorType.receiveTimeout:{return HttpException(code: -1, msg: 'receive timeout');}case DioErrorType.response:{try {int statusCode = error.response?.statusCode ?? 0;// String errMsg = error.response.statusMessage;// return ErrorEntity(code: errCode, message: errMsg);switch (statusCode) {case 400:{return HttpException(code: statusCode, msg: 'Request syntax error');}case 401:{return HttpException(code: statusCode, msg: 'Without permission');}case 403:{return HttpException(code: statusCode, msg: 'Server rejects execution');}case 404:{return HttpException(code: statusCode, msg: 'Unable to connect to server');}case 405:{return HttpException(code: statusCode, msg: 'The request method is disabled');}case 500:{return HttpException(code: statusCode, msg: 'Server internal error');}case 502:{return HttpException(code: statusCode, msg: 'Invalid request');}case 503:{return HttpException(code: statusCode, msg: 'The server is down.');}case 505:{return HttpException(code: statusCode, msg: 'HTTP requests are not supported');}default:{return HttpException(code: statusCode, msg: error.response?.statusMessage ?? 'unknow error');}}} on Exception catch (_) {return HttpException(code: -1, msg: 'unknow error');}}default:{return HttpException(code: -1, msg: error.message);}}}
}

class HttpOptions {/// 超时时间;单位是msstatic const int connectTimeout = 15000;static const int receiveTimeout = 15000;static const int sendTimeout = 15000;/// 地址域名前缀static const String baseUrl = '************';}

/// 调用底层的request,重新提供get,post等方便方法
class HttpUtils {static HttpRequest httpRequest = HttpRequest();/// getstatic Future get({required String path,Map? queryParameters,bool showLoading = true,bool showErrorMessage = true,}) {return httpRequest.request(path: path,method: HttpMethod.get,queryParameters: queryParameters,showLoading: showLoading,showErrorMessage: showErrorMessage,);}/// poststatic Future post({required String path,required HttpMethod method,dynamic data,bool showLoading = true,bool showErrorMessage = true,}) {return httpRequest.request(path: path,method: HttpMethod.post,data: data,showLoading: showLoading,showErrorMessage: showErrorMessage,);}}

相关内容

热门资讯

原创 二... 10. 迪士尼经典翻车?《白雪公主》2.11亿美元票房大跌引发争议 电影解说:迪士尼真人版《白雪公主...
原创 全... 1 一份现象级成绩单引爆关注 最近这几年是中国各地旅游产业爆发式增长时期。 从山东淄博烧烤、甘肃天水...
为什么说活到老学到老 为什么说活到老学到老因为世界上要学习的知识和技能有很多,多到学不完。学到的东西又能给人很大的帮助,所...
儿子夺去父亲失地农民去告他可以... 儿子夺去父亲失地农民去告他可以归还吗?告你 他养你这么多年。付出多少心血你记得是谁喂你吃饭。是谁教你...
莎翁的《仲夏夜之梦》中心思想是... 莎翁的《仲夏夜之梦》中心思想是什么?主要要表达什么思想,或想要说什么?爱情和胡闹,命运的不自主,被人...
我们班的女生都说我很萌,很纯,... 我们班的女生都说我很萌,很纯,一直叫我正太。请问正太到底是什么意思。说通俗一点、就是很可爱、很萌的男...
唱歌卓玛脚本怎么写的 唱歌卓玛脚本怎么写的唱歌卓玛脚本一般需要遵循一定的规范和流程来完成。首先,需要编写语音合成引擎和自然...
《一人之下》里三十六贼中幸存的... 《一人之下》里三十六贼中幸存的都有谁?张怀义(张锡林),无根生,风天养,郑子布,周圣。端木瑛,马本在...
古代有哪些女性很有才华? 古代有哪些女性很有才华?才华横溢,留有作品李清照——最有才华的女人 红藕香残玉簟秋。轻解罗裳,独...
怎样教小孩英语 怎样教小孩英语小孩子刚开始学英语可能更重要的是音感,也就是英语的语调和发音的感觉。个人觉得你可能可以...
还有没有像“谁养鱼”这样的智力... 还有没有像“谁养鱼”这样的智力题? 5个海盗抢得100枚金币后,讨论如何进行公正分配。他们商定的分...
怎样看待那些整天秀恩爱的人? 怎样看待那些整天秀恩爱的人?有些名人比较低调,而有些名人就是大大方方地让大家知道他们的幸福,粉丝们也...
余光中的星之葬配什么图好看 余光中的星之葬配什么图好看
写自己的10个优点 写自己的10个优点 下面是我的十个优点,与你分享:1、文静中不乏活泼----动与静的结合2、幽默--...
王刚讲故事猫鼠游戏的结局 王刚讲故事猫鼠游戏的结局尽量详细。谢谢!冷江向小白狐求婚
明代三言二拍的作者是谁 明代三言二拍的作者是谁三言二拍是指明代五本著名传奇短篇小说集及拟话本集的合称。“三言”即《喻世明言》...
天蝎座女喜欢什么 天蝎座女喜欢什么天蝎座女生一般都是很神秘的,而且非常善于隐藏自己的内心,她们很注重细节,在别人眼中她...
红军一步一步怎么画 红军一步一步怎么画第一步,我们画出小红军的帽子,然后在帽子上画出帽沿,并画出帽子上的五角星。第二步,...
20万个为什么 20万个为什么这是10万个为什么的哥哥??20万个?30万个为什么
“爱莫能及”是什么意思? “爱莫能及”是什么意思?意思是:虽然心中关切同情,却没有力量触及(某件事情或领域)。等同于爱莫能助。...