热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Flutter完整的Dio网络框架null空安全二次封装。

所需依赖添加在项目中的pubspec.yaml中:dio:^4.0.6#网络请求connectivity_plus:^2.3.6#网络监测pretty_dio_l

所需依赖添加在项目中的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,);}}

推荐阅读
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • SpringBoot uri统一权限管理的实现方法及步骤详解
    本文详细介绍了SpringBoot中实现uri统一权限管理的方法,包括表结构定义、自动统计URI并自动删除脏数据、程序启动加载等步骤。通过该方法可以提高系统的安全性,实现对系统任意接口的权限拦截验证。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
  • 重入锁(ReentrantLock)学习及实现原理
    本文介绍了重入锁(ReentrantLock)的学习及实现原理。在学习synchronized的基础上,重入锁提供了更多的灵活性和功能。文章详细介绍了重入锁的特性、使用方法和实现原理,并提供了类图和测试代码供读者参考。重入锁支持重入和公平与非公平两种实现方式,通过对比和分析,读者可以更好地理解和应用重入锁。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文介绍了Java高并发程序设计中线程安全的概念与synchronized关键字的使用。通过一个计数器的例子,演示了多线程同时对变量进行累加操作时可能出现的问题。最终值会小于预期的原因是因为两个线程同时对变量进行写入时,其中一个线程的结果会覆盖另一个线程的结果。为了解决这个问题,可以使用synchronized关键字来保证线程安全。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
  • 本文介绍了Java中Hashtable的clear()方法,该方法用于清除和移除指定Hashtable中的所有键。通过示例程序演示了clear()方法的使用。 ... [详细]
  • 本文整理了Java面试中常见的问题及相关概念的解析,包括HashMap中为什么重写equals还要重写hashcode、map的分类和常见情况、final关键字的用法、Synchronized和lock的区别、volatile的介绍、Syncronized锁的作用、构造函数和构造函数重载的概念、方法覆盖和方法重载的区别、反射获取和设置对象私有字段的值的方法、通过反射创建对象的方式以及内部类的详解。 ... [详细]
author-avatar
玉乔嘉芸孟峰
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有