DioUtil.dart 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import 'package:deus_app/common/local/StoreHelper.dart';
  2. import 'package:deus_app/common/utils/ConstantString.dart';
  3. import 'package:dio/dio.dart';
  4. import 'package:flutter_easyloading/flutter_easyloading.dart';
  5. import 'package:pretty_dio_logger/pretty_dio_logger.dart';
  6. /// 请求方法
  7. enum DioMethod {
  8. get,
  9. post,
  10. put,
  11. delete,
  12. patch,
  13. head,
  14. }
  15. class DioUtil {
  16. /// 单例模式
  17. static DioUtil? _instance;
  18. factory DioUtil() => _instance ?? DioUtil._internal();
  19. static DioUtil? get instance => _instance ?? DioUtil._internal();
  20. /// 连接超时时间
  21. static const int connectTimeout = 30 * 1000;
  22. /// 响应超时时间
  23. static const int receiveTimeout = 30 * 1000;
  24. /// Dio实例
  25. static Dio _dio = Dio();
  26. /// 初始化
  27. DioUtil._internal() {
  28. // 初始化基本选项
  29. BaseOptions options = BaseOptions(
  30. baseUrl: 'https://fqgz.flowbb.cn:7070/system-api/',
  31. connectTimeout: connectTimeout,
  32. receiveTimeout: receiveTimeout);
  33. _instance = this;
  34. // 初始化dio
  35. _dio = Dio(options);
  36. // 添加拦截器
  37. _dio.interceptors.add(InterceptorsWrapper(
  38. onRequest: _onRequest, onResponse: _onResponse, onError: _onError));
  39. _dio.interceptors.add(PrettyDioLogger(requestHeader: true, requestBody:
  40. true, responseHeader: true));
  41. }
  42. /// 请求拦截器
  43. void _onRequest(RequestOptions options, RequestInterceptorHandler handler) {
  44. // 对非open的接口的请求参数全部增加userId
  45. if (!options.path.contains("open")) {
  46. options.queryParameters["userId"] = "xxx";
  47. }
  48. // 头部添加token
  49. options.headers["Authorization"] = StoreHelper.getStorage(ConstantString.token);
  50. // 更多业务需求
  51. handler.next(options);
  52. // super.onRequest(options, handler);
  53. }
  54. /// 相应拦截器
  55. void _onResponse(
  56. Response response, ResponseInterceptorHandler handler) async {
  57. // 请求成功是对数据做基本处理
  58. if (response.statusCode == 200) {
  59. // ....
  60. handler.next(response);
  61. } else {
  62. // ....
  63. // showToast(response.statusMessage);
  64. }
  65. if (response.requestOptions.baseUrl.contains("???????")) {
  66. // 对某些单独的url返回数据做特殊处理
  67. }
  68. }
  69. /// 错误处理
  70. void _onError(DioError error, ErrorInterceptorHandler handler) {
  71. handler.next(error);
  72. }
  73. /// 请求类
  74. Future<T> request<T>(
  75. String path, {
  76. DioMethod method = DioMethod.get,
  77. Map<String, dynamic>? params,
  78. data,
  79. CancelToken? cancelToken,
  80. Options? options,
  81. ProgressCallback? onSendProgress,
  82. ProgressCallback? onReceiveProgress,
  83. }) async {
  84. const _methodValues = {
  85. DioMethod.get: 'get',
  86. DioMethod.post: 'post',
  87. DioMethod.put: 'put',
  88. DioMethod.delete: 'delete',
  89. DioMethod.patch: 'patch',
  90. DioMethod.head: 'head'
  91. };
  92. EasyLoading.show(status: 'loading...');
  93. options ??= Options(method: _methodValues[method]);
  94. try {
  95. Response response;
  96. response = await _dio.request(path,
  97. data: data,
  98. queryParameters: params,
  99. cancelToken: cancelToken,
  100. options: options,
  101. onSendProgress: onSendProgress,
  102. onReceiveProgress: onReceiveProgress);
  103. EasyLoading.dismiss();
  104. return response.data;
  105. } on DioError catch (e) {
  106. EasyLoading.dismiss();
  107. // showToast(e.message);
  108. return e.response?.data;
  109. }
  110. }
  111. /// 开启日志打印
  112. /// 需要打印日志的接口在接口请求前 DioUtil.instance?.openLog();
  113. void openLog() {
  114. _dio.interceptors
  115. .add(LogInterceptor(responseHeader: false, responseBody: true));
  116. }
  117. }