Flutter Dio二次封装的实现

Flutter Dio二次封装的实现,第1张

概述Flutter Dio二次封装的实现 目录: DioManager:Dio辅助类NWMethod:请求方法,get.post等 NWApi:大家都知道 EntityFactory:json转换辅助工厂,把json转为T BaseEntity<T>:数据基类,返回的参数为 {"code": 0, "message": "", "data": {}} BaseListEntity<T>:数据基类2,返回的参数为 {"code ...

目录:

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

EntityFactory:

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:

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:

class BaseListEntity<T> { int code; String message; List<T> data; BaseListEntity({this.code,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"],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";//接口返回:{"code": int,"message": "String","data": {"account": "String","password": "String"}} static final queryListPath = "/query/List";//接口返回:{"code": ing,"data": [int,int,String,int]} static final queryListJsonPath = "/query/ListJson";//接口返回:{"code": int,"data": [{"account": "String","password": "String"}, {"account": "String","password": "String"}]}}

NWMethod:

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进行一些全局的参数设置:

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,“data”: {}} 和 {“code”: 0,“data”: []} 这两种数据是要分开两个请求方法的:

 // 请求,返回参数为 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,Function(List) success,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:

 // 错误信息 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 类代码:

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,);   dio = dio(options);  } } // 请求,返回参数为 T // method:请求方法,NWMethod.POST等 // path:请求地址 // params:请求参数 // success:请求成功回调 // error:请求失败回调 Future request<T>(NWMethod method,Function(List<T>) success,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.RESPONSE:{    try {     int errCode = error.response.statusCode;     String errMsg = error.response.statusMessage;     return ErrorEntity(code: "$errCode",message: error.message);   }  } }}

使用:

// 返回 LoginEntitydioManager().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}"); });// 返回 ListdioManager().requestList<LoginEntity>( NWMethod.POST,NWAPI.queryListJsonPath,massage = ${error.message}"); });

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

总结

以上是内存溢出为你收集整理的Flutter Dio二次封装的实现全部内容,希望文章能够帮你解决Flutter Dio二次封装的实现所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1144219.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存