服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Flutter Dio二次封装的实现

Flutter Dio二次封装的实现

2022-11-14 14:37头发还没秃 Android

这篇文章主要介绍了Flutter Dio二次封装的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

目录:

  • DioManager:Dio辅助类NWMethod:请求方法,get、post等
  • NWApi:大家都知道
  • EntityFactory:json转换辅助工厂,把json转为T
  • BaseEntity<T>:数据基类,返回的参数为 {“code”: 0, “message”: “”, “data”: {}}
  • BaseListEntity<T>:数据基类2,返回的参数为 {“code”: 0, “message”: “”, “data”: []}
  • ErrorEntity:请求报错基类,{“code”: 0, “message”: “”}

EntityFactory:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class EntityFactory {
 static T generateOBJ<T>(json) {
  if (json == null) {
   return null;
  }
//可以在这里加入任何需要并且可以转换的类型,例如下面
//  else if (T.toString() == "LoginEntity") {
//   return LoginEntity.fromJson(json) as T;
//  }
  else {
   return json as T;
  }
 }
}

BaseEntity:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class BaseEntity<T> {
 int code;
 String message;
 T data;
 
 BaseEntity({this.code, this.message, this.data});
 
 factory BaseEntity.fromJson(json) {
  return BaseEntity(
   code: json["code"],
   message: json["msg"],
   // data值需要经过工厂转换为我们传进来的类型
   data: EntityFactory.generateOBJ<T>(json["data"]),
  );
 }
}

BaseListEntity:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class BaseListEntity<T> {
 int code;
 String message;
 List<T> data;
 
 BaseListEntity({this.code, this.message, this.data});
 
 factory BaseListEntity.fromJson(json) {
  List<T> mData = List();
  if (json['data'] != null) {
   //遍历data并转换为我们传进来的类型
   (json['data'] as List).forEach((v) {
    mData.add(EntityFactory.generateOBJ<T>(v));
   });
  }
 
  return BaseListEntity(
   code: json["code"],
   message: json["msg"],
   data: mData,
  );
 } }

ErrorEntity:

?
1
2
3
4
5
class ErrorEntity {
 int code;
 String message;
 ErrorEntity({this.code, this.message});
}

NWApi:

?
1
2
3
4
5
6
class NWApi {
 static final baseApi = "https://easy-mock.bookset.io/mock/5dfae67d4946c20a50841fa7/example/";
 static final loginPath = "user/login";//接口返回:{"code": int, "message": "String", "data": {"account": "String", "password": "String"}}
 static final queryListPath = "/query/list";//接口返回:{"code": ing, "message": "String", "data": [int, int, String, int, String, int]}
 static final queryListJsonPath = "/query/listjson";//接口返回:{"code": int, "message": "String", "data": [{"account": "String", "password": "String"}, {"account": "String", "password": "String"}]}
}

NWMethod:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
enum NWMethod {
 GET,
 POST,
 DELETE,
 PUT
}
//使用:NWMethodValues[NWMethod.POST]
const NWMethodValues = {
 NWMethod.GET: "get",
 NWMethod.POST: "post",
 NWMethod.DELETE: "delete",
 NWMethod.PUT: "put"
};

下面就可以进行正式的封装了:

第一步是创建Dio的单例辅助类,并初始化Dio和对Dio进行一些全局的参数设置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import 'package:dio/dio.dart';
import 'package:flutter_app/network/NWApi.dart';
import 'package:flutter_app/utils/PrintUtil.dart';
class DioManager {
 static final DioManager _shared = DioManager._internal();
 factory DioManager() => _shared;
 Dio dio;
 DioManager._internal() {
  if (dio == null) {
   BaseOptions options = BaseOptions(
    baseUrl: NWApi.baseApi,
    contentType: Headers.jsonContentType,
    responseType: ResponseType.json,
    receiveDataWhenStatusError: false,
    connectTimeout: 30000,
    receiveTimeout: 3000,
   );
   dio = Dio(options);
  }
 }
}

第二步对请求进行封装,在我的想法中 {“code”: 0, “message”: “”, “data”: {}} 和 {“code”: 0, “message”: “”, “data”: []} 这两种数据是要分开两个请求方法的:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 请求,返回参数为 T
// method:请求方法,NWMethod.POST等
// path:请求地址
// params:请求参数
// success:请求成功回调
// error:请求失败回调
Future request<T>(NWMethod method, String path, {Map params, Function(T) success, Function(ErrorEntity) error}) async {
 try {
  Response response = await dio.request(path, queryParameters: params, options: Options(method: NWMethodValues[method]));
  if (response != null) {
   BaseEntity entity = BaseEntity<T>.fromJson(response.data);
   if (entity.code == 0) {
    success(entity.data);
   } else {
    error(ErrorEntity(code: entity.code, message: entity.message));
   }
  } else {
   error(ErrorEntity(code: -1, message: "未知错误"));
  }
 } on DioError catch(e) {
  error(createErrorEntity(e));
 }
}
 
// 请求,返回参数为 List
// method:请求方法,NWMethod.POST等
// path:请求地址
// params:请求参数
// success:请求成功回调
// error:请求失败回调
Future requestList<T>(NWMethod method, String path, {Map params, Function(List) success, Function(ErrorEntity) error}) async {
 try {
  Response response = await dio.request(path, queryParameters: params, options: Options(method: NWMethodValues[method]));
  if (response != null) {
   BaseListEntity entity = BaseListEntity<T>.fromJson(response.data);
   if (entity.code == 0) {
    success(entity.data);
   } else {
    error(ErrorEntity(code: entity.code, message: entity.message));
   }
  } else {
    error(ErrorEntity(code: -1, message: "未知错误"));
  }
 } on DioError catch(e) {
  error(createErrorEntity(e));
 }
}

提取请求错误处理方法createErrorEntity:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// 错误信息
 ErrorEntity createErrorEntity(DioError error) {
  switch (error.type) {
   case DioErrorType.CANCEL:{
    return ErrorEntity(code: -1, message: "请求取消");
   }
   break;
   case DioErrorType.CONNECT_TIMEOUT:{
    return ErrorEntity(code: -1, message: "连接超时");
   }
   break;
   case DioErrorType.SEND_TIMEOUT:{
    return ErrorEntity(code: -1, message: "请求超时");
   }
   break;
   case DioErrorType.RECEIVE_TIMEOUT:{
    return ErrorEntity(code: -1, message: "响应超时");
   }
   break;
   case DioErrorType.RESPONSE:{
    try {
     int errCode = error.response.statusCode;
     String errMsg = error.response.statusMessage;
     return ErrorEntity(code: errCode, message: errMsg);
//     switch (errCode) {
//      case 400: {
//       return ErrorEntity(code: errCode, message: "请求语法错误");
//      }
//      break;
//      case 403: {
//       return ErrorEntity(code: errCode, message: "服务器拒绝执行");
//      }
//      break;
//      case 404: {
//       return ErrorEntity(code: errCode, message: "无法连接服务器");
//      }
//      break;
//      case 405: {
//       return ErrorEntity(code: errCode, message: "请求方法被禁止");
//      }
//      break;
//      case 500: {
//       return ErrorEntity(code: errCode, message: "服务器内部错误");
//      }
//      break;
//      case 502: {
//       return ErrorEntity(code: errCode, message: "无效的请求");
//      }
//      break;
//      case 503: {
//       return ErrorEntity(code: errCode, message: "服务器挂了");
//      }
//      break;
//      case 505: {
//       return ErrorEntity(code: errCode, message: "不支持HTTP协议请求");
//      }
//      break;
//      default: {
//       return ErrorEntity(code: errCode, message: "未知错误");
//      }
//     }
    } on Exception catch(_) {
     return ErrorEntity(code: -1, message: "未知错误");
    }
   }
   break;
   default: {
    return ErrorEntity(code: -1, message: error.message);
   }
  }
 }

完整的 DioManager 类代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import 'package:dio/dio.dart';
import 'package:flutter_app/network/entity/BaseEntity.dart';
import 'package:flutter_app/network/entity/BaseListEntity.dart';
import 'package:flutter_app/network/entity/EntityFactory.dart';
import 'package:flutter_app/network/entity/ErrorEntity.dart';
import 'package:flutter_app/network/NWApi.dart';
import 'package:flutter_app/network/NWMethod.dart';
class DioManager {
 static final DioManager _shared = DioManager._internal();
 factory DioManager() => _shared;
 Dio dio;
 DioManager._internal() {
  if (dio == null) {
   BaseOptions options = BaseOptions(
    baseUrl: NWApi.baseApi,
    contentType: Headers.jsonContentType,
    responseType: ResponseType.json,
    receiveDataWhenStatusError: false,
    connectTimeout: 30000,
    receiveTimeout: 3000,
   );
   dio = Dio(options);
  }
 }
 
 // 请求,返回参数为 T
 // method:请求方法,NWMethod.POST等
 // path:请求地址
 // params:请求参数
 // success:请求成功回调
 // error:请求失败回调
 Future request<T>(NWMethod method, String path, {Map params, Function(T) success, Function(ErrorEntity) error}) async {
  try {
   Response response = await dio.request(path, queryParameters: params, options: Options(method: NWMethodValues[method]));
   if (response != null) {
    BaseEntity entity = BaseEntity<T>.fromJson(response.data);
    if (entity.code == 0) {
     success(entity.data);
    } else {
     error(ErrorEntity(code: entity.code, message: entity.message));
    }
   } else {
    error(ErrorEntity(code: -1, message: "未知错误"));
   }
  } on DioError catch(e) {
   error(createErrorEntity(e));
  }
 }
 
 // 请求,返回参数为 List
 // method:请求方法,NWMethod.POST等
 // path:请求地址
 // params:请求参数
 // success:请求成功回调
 // error:请求失败回调
 Future requestList<T>(NWMethod method, String path, {Map params, Function(List<T>) success, Function(ErrorEntity) error}) async {
  try {
   Response response = await dio.request(path, queryParameters: params, options: Options(method: NWMethodValues[method]));
   if (response != null) {
    BaseListEntity entity = BaseListEntity<T>.fromJson(response.data);
    if (entity.code == 0) {
     success(entity.data);
    } else {
     error(ErrorEntity(code: entity.code, message: entity.message));
    }
   } else {
    error(ErrorEntity(code: -1, message: "未知错误"));
   }
  } on DioError catch(e) {
   error(createErrorEntity(e));
  }
 }
 
 // 错误信息
 ErrorEntity createErrorEntity(DioError error) {
  switch (error.type) {
   case DioErrorType.CANCEL:{
    return ErrorEntity(code: -1, message: "请求取消");
   }
   break;
   case DioErrorType.CONNECT_TIMEOUT:{
    return ErrorEntity(code: -1, message: "连接超时");
   }
   break;
   case DioErrorType.SEND_TIMEOUT:{
    return ErrorEntity(code: -1, message: "请求超时");
   }
   break;
   case DioErrorType.RECEIVE_TIMEOUT:{
    return ErrorEntity(code: -1, message: "响应超时");
   }
   break;
   case DioErrorType.RESPONSE:{
    try {
     int errCode = error.response.statusCode;
     String errMsg = error.response.statusMessage;
     return ErrorEntity(code: "$errCode", message: errMsg);
//     switch (errCode) {
//      case 400: {
//       return ErrorEntity(code: errCode, message: "请求语法错误");
//      }
//      break;
//      case 403: {
//       return ErrorEntity(code: errCode, message: "服务器拒绝执行");
//      }
//      break;
//      case 404: {
//       return ErrorEntity(code: errCode, message: "无法连接服务器");
//      }
//      break;
//      case 405: {
//       return ErrorEntity(code: errCode, message: "请求方法被禁止");
//      }
//      break;
//      case 500: {
//       return ErrorEntity(code: errCode, message: "服务器内部错误");
//      }
//      break;
//      case 502: {
//       return ErrorEntity(code: errCode, message: "无效的请求");
//      }
//      break;
//      case 503: {
//       return ErrorEntity(code: errCode, message: "服务器挂了");
//      }
//      break;
//      case 505: {
//       return ErrorEntity(code: errCode, message: "不支持HTTP协议请求");
//      }
//      break;
//      default: {
//       return ErrorEntity(code: errCode, message: "未知错误");
//      }
//     }
    } on Exception catch(_) {
     return ErrorEntity(code: -1, message: "未知错误");
    }
   }
   break;
   default: {
    return ErrorEntity(code: -1, message: error.message);
   }
  }
 }
}

使用:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 返回 LoginEntity
DioManager().request<LoginEntity>(
 NWMethod.POST,
 NWApi.loginPath,
 params: {"account": "421789838@qq.com", "password": "123456"},
 success: (data) {
   print("success data = $data"});
 }, error: (error) {
   print("error code = ${error.code}, massage = ${error.message}");
 }
);
 
// 返回 List
DioManager().requestList<LoginEntity>(
 NWMethod.POST,
 NWApi.queryListJsonPath,
 params: {"account": "421789838@qq.com", "password": "123456"},
 success: (data) {
   print("success data = $data"});
 }, error: (error) {
   print("error code = ${error.code}, massage = ${error.message}");
 }
);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://juejin.im/post/5e158957f265da5d637fff8c

延伸 · 阅读

精彩推荐