The realization of the second encapsulation of flutter Dio

Time:2020-4-17

Catalog:

  • Diomanager: DIO auxiliary class nwmethod: request method, get, post, etc
  • Nwapi: as you all know
  • Entityfactory: JSON conversion auxiliary factory, convert JSON to t
  • Baseentity < T >: data base class. The returned parameters are {“code”: 0, “message”: “”, “data”: {}}}
  • Baselistentity < T >: data base class 2, the returned parameter is {“code”: 0, “message”: “”, “data”: []}
  • Errorentity: request error base class, {“code”: 0, “message”: “”}

EntityFactory:

class EntityFactory {
 static T generateOBJ<T>(json) {
  if (json == null) {
   return null;
  }
//You can add any type you need and 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"],
   //The data value needs to be factory converted to the type we passed in
   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) {
   //Traverse data and convert 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"; // the interface returns: {"code": int, "message": "string", "data": {"account": "string", "password": "string"}}
 Static final querylistpath = "/ query / list"; // the interface returns: {"code": ing, "message": "string", "data": [int, int, string, int, string, int]}
 Static final querylistjsonpath = "/ query / listjson"; // the 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 encapsulated:

The first step is to create a single auxiliary class of DIO, initialize DIO and set some global parameters 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);
  }
 }
}

The second step is to encapsulate the request. In my mind, {“code”: 0, “message”: “”, “data”: {}} and {“code”: 0, “message”: “”, “data”: []} are two kinds of data to separate the two request methods:

//Request, return parameter is t
 //Method: request method, nwmethod.post, etc
 //Path: request address
 //Params: request parameters
 //Success: request successful callback
 //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, return parameter is list
 //Method: request method, nwmethod.post, etc
 //Path: request address
 //Params: request parameters
 //Success: request successful callback
 //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 refused 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 forbidden");
//      }
//      break;
//      case 500: {
//Return errorentity (Code: errCode, message: "internal server error");
//      }
//      break;
//      case 502: {
//Return errorentity (Code: errCode, message: "invalid request");
//      }
//      break;
//      case 503: {
//Return errorentity (Code: errCode, message: "server hung");
//      }
//      break;
//      case 505: {
//Return errorentity (Code: errCode, message: "HTTP protocol request is not supported");
//      }
//      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, return parameter is t
 //Method: request method, nwmethod.post, etc
 //Path: request address
 //Params: request parameters
 //Success: request successful callback
 //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, return parameter is list
 //Method: request method, nwmethod.post, etc
 //Path: request address
 //Params: request parameters
 //Success: request successful callback
 //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 refused 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 forbidden");
//      }
//      break;
//      case 500: {
//Return errorentity (Code: errCode, message: "internal server error");
//      }
//      break;
//      case 502: {
//Return errorentity (Code: errCode, message: "invalid request");
//      }
//      break;
//      case 503: {
//Return errorentity (Code: errCode, message: "server hung");
//      }
//      break;
//      case 505: {
//Return errorentity (Code: errCode, message: "HTTP protocol request is not supported");
//      }
//      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:

//Return to loginentity
DioManager().request<LoginEntity>(
 NWMethod.POST,
 NWApi.loginPath,
 params: {"account": "[email protected]", "password": "123456"},
 success: (data) {
   print("success data = $data"});
 }, error: (error) {
   print("error code = ${error.code}, massage = ${error.message}");
 }
);

//Return to list
DioManager().requestList<LoginEntity>(
 NWMethod.POST,
 NWApi.queryListJsonPath,
 params: {"account": "[email protected]", "password": "123456"},
 success: (data) {
   print("success data = $data"});
 }, error: (error) {
   print("error code = ${error.code}, massage = ${error.message}");
 }
);

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.