Realization of Flutter Dio Secondary Encapsulation
- 2021-11-14 07:15:42
- OfStack
Directory:
DioManager: Dio Helper Class NWMethod: Request Method, get, post, etc NWApi: Everybody knows EntityFactory: json conversion auxiliary factory, json to T BaseEntity < T > : Database class that returns parameters {"code": 0, "message": "," data ": {}} BaseListEntity < T > Database Class 2, which returns {"code": 0, "message": "," data ": []} ErrorEntity: Request error reporting base class, {"code": 0, "message": "}
EntityFactory:
class EntityFactory {
static T generateOBJ<T>(json) {
if (json == null) {
return null;
}
// You can add any type that you need and can convert here, such as the following
// else if (T.toString() == "LoginEntity") {
// return LoginEntity.fromJson(json) as T;
// }
else {
return json as T;
}
}
}
BaseEntity:
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 The value needs to be converted to the type we passed in by the factory
data: EntityFactory.generateOBJ<T>(json["data"]),
);
}
}
BaseListEntity:
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) {
// Traversal data And convert it to the type we passed in
(json['data'] as List).forEach((v) {
mData.add(EntityFactory.generateOBJ<T>(v));
});
}
return BaseListEntity(
code: json["code"],
message: json["msg"],
data: mData,
);
} }
ErrorEntity:
class ErrorEntity {
int code;
String message;
ErrorEntity({this.code, this.message});
}
NWApi:
class NWApi {
static final baseApi = "https://easy-mock.bookset.io/mock/5dfae67d4946c20a50841fa7/example/";
static final loginPath = "user/login";// Interface returns: {"code": int, "message": "String", "data": {"account": "String", "password": "String"}}
static final queryListPath = "/query/list";// Interface returns: {"code": ing, "message": "String", "data": [int, int, String, int, String, int]}
static final queryListJsonPath = "/query/listjson";// Interface returns: {"code": int, "message": "String", "data": [{"account": "String", "password": "String"} , {"account": "String", "password": "String"}]}
}
NWMethod:
enum NWMethod {
GET,
POST,
DELETE,
PUT
}
// Use: NWMethodValues[NWMethod.POST]
const NWMethodValues = {
NWMethod.GET: "get",
NWMethod.POST: "post",
NWMethod.DELETE: "delete",
NWMethod.PUT: "put"
};
The following can be formally packaged:
The first step is to create a singleton helper class for Dio, initialize Dio and make some global parameter settings for Dio:
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);
}
}
}
Step 2 encapsulates the request. In my mind, {"code": 0, "message": "," data ": {}} and {" code ": 0," message ":", "data": []} These two types of data are intended to separate the two request methods:
// Request, the return parameter is T
// method Request method, NWMethod.POST Etc
// path Request address
// params Request parameters
// success Successful callback requested
// error Request failed callback
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: " Unknown error "));
}
} on DioError catch(e) {
error(createErrorEntity(e));
}
}
// Request, the return parameter is List
// method Request method, NWMethod.POST Etc
// path Request address
// params Request parameters
// success Successful callback requested
// error Request failed callback
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: " Unknown error "));
}
} on DioError catch(e) {
error(createErrorEntity(e));
}
}
Extract request error handling method createErrorEntity:
// Error message
ErrorEntity createErrorEntity(DioError error) {
switch (error.type) {
case DioErrorType.CANCEL:{
return ErrorEntity(code: -1, message: " Request cancellation ");
}
break;
case DioErrorType.CONNECT_TIMEOUT:{
return ErrorEntity(code: -1, message: " Connection timeout ");
}
break;
case DioErrorType.SEND_TIMEOUT:{
return ErrorEntity(code: -1, message: " Request timeout ");
}
break;
case DioErrorType.RECEIVE_TIMEOUT:{
return ErrorEntity(code: -1, message: " Response timeout ");
}
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: " Request syntax error ");
// }
// break;
// case 403: {
// return ErrorEntity(code: errCode, message: " Server refuses to execute ");
// }
// break;
// case 404: {
// return ErrorEntity(code: errCode, message: " Unable to connect to server ");
// }
// break;
// case 405: {
// return ErrorEntity(code: errCode, message: " Request method is prohibited ");
// }
// break;
// case 500: {
// return ErrorEntity(code: errCode, message: " Server internal error ");
// }
// break;
// case 502: {
// return ErrorEntity(code: errCode, message: " Invalid request ");
// }
// break;
// case 503: {
// return ErrorEntity(code: errCode, message: " The server is down ");
// }
// break;
// case 505: {
// return ErrorEntity(code: errCode, message: " Not supported HTTP Protocol request ");
// }
// break;
// default: {
// return ErrorEntity(code: errCode, message: " Unknown error ");
// }
// }
} on Exception catch(_) {
return ErrorEntity(code: -1, message: " Unknown error ");
}
}
break;
default: {
return ErrorEntity(code: -1, message: error.message);
}
}
}
Complete DioManager class code:
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);
}
}
// Request, the return parameter is T
// method Request method, NWMethod.POST Etc
// path Request address
// params Request parameters
// success Successful callback requested
// error Request failed callback
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: " Unknown error "));
}
} on DioError catch(e) {
error(createErrorEntity(e));
}
}
// Request, the return parameter is List
// method Request method, NWMethod.POST Etc
// path Request address
// params Request parameters
// success Successful callback requested
// error Request failed callback
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: " Unknown error "));
}
} on DioError catch(e) {
error(createErrorEntity(e));
}
}
// Error message
ErrorEntity createErrorEntity(DioError error) {
switch (error.type) {
case DioErrorType.CANCEL:{
return ErrorEntity(code: -1, message: " Request cancellation ");
}
break;
case DioErrorType.CONNECT_TIMEOUT:{
return ErrorEntity(code: -1, message: " Connection timeout ");
}
break;
case DioErrorType.SEND_TIMEOUT:{
return ErrorEntity(code: -1, message: " Request timeout ");
}
break;
case DioErrorType.RECEIVE_TIMEOUT:{
return ErrorEntity(code: -1, message: " Response timeout ");
}
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: " Request syntax error ");
// }
// break;
// case 403: {
// return ErrorEntity(code: errCode, message: " Server refuses to execute ");
// }
// break;
// case 404: {
// return ErrorEntity(code: errCode, message: " Unable to connect to server ");
// }
// break;
// case 405: {
// return ErrorEntity(code: errCode, message: " Request method is prohibited ");
// }
// break;
// case 500: {
// return ErrorEntity(code: errCode, message: " Server internal error ");
// }
// break;
// case 502: {
// return ErrorEntity(code: errCode, message: " Invalid request ");
// }
// break;
// case 503: {
// return ErrorEntity(code: errCode, message: " The server is down ");
// }
// break;
// case 505: {
// return ErrorEntity(code: errCode, message: " Not supported HTTP Protocol request ");
// }
// break;
// default: {
// return ErrorEntity(code: errCode, message: " Unknown error ");
// }
// }
} on Exception catch(_) {
return ErrorEntity(code: -1, message: " Unknown error ");
}
}
break;
default: {
return ErrorEntity(code: -1, message: error.message);
}
}
}
}
Use:
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 The value needs to be converted to the type we passed in by the factory
data: EntityFactory.generateOBJ<T>(json["data"]),
);
}
}
0