Flutter Dio二次封装的实现
目录:
- DioManager:Dio辅助类NWMethod:请求方法,get、post等
- NWApi:大家都知道
- EntityFactory:json转换辅助工厂,把json转为T
- BaseEntity
:数据基类,返回的参数为{“code”:0,“message”:“”,“data”:{}} - BaseListEntity
:数据基类2,返回的参数为{“code”:0,“message”:“”,“data”:[]} - ErrorEntity:请求报错基类,{“code”:0,“message”:“”}
EntityFactory:
classEntityFactory{ staticTgenerateOBJ(json){ if(json==null){ returnnull; } //可以在这里加入任何需要并且可以转换的类型,例如下面 //elseif(T.toString()=="LoginEntity"){ //returnLoginEntity.fromJson(json)asT; //} else{ returnjsonasT; } } }
BaseEntity:
classBaseEntity{ intcode; Stringmessage; Tdata; BaseEntity({this.code,this.message,this.data}); factoryBaseEntity.fromJson(json){ returnBaseEntity( code:json["code"], message:json["msg"], //data值需要经过工厂转换为我们传进来的类型 data:EntityFactory.generateOBJ (json["data"]), ); } }
BaseListEntity:
classBaseListEntity{ intcode; Stringmessage; List data; BaseListEntity({this.code,this.message,this.data}); factoryBaseListEntity.fromJson(json){ List mData=List(); if(json['data']!=null){ //遍历data并转换为我们传进来的类型 (json['data']asList).forEach((v){ mData.add(EntityFactory.generateOBJ (v)); }); } returnBaseListEntity( code:json["code"], message:json["msg"], data:mData, ); }}
ErrorEntity:
classErrorEntity{ intcode; Stringmessage; ErrorEntity({this.code,this.message}); }
NWApi:
classNWApi{ staticfinalbaseApi="https://easy-mock.bookset.io/mock/5dfae67d4946c20a50841fa7/example/"; staticfinalloginPath="user/login";//接口返回:{"code":int,"message":"String","data":{"account":"String","password":"String"}} staticfinalqueryListPath="/query/list";//接口返回:{"code":ing,"message":"String","data":[int,int,String,int,String,int]} staticfinalqueryListJsonPath="/query/listjson";//接口返回:{"code":int,"message":"String","data":[{"account":"String","password":"String"},{"account":"String","password":"String"}]} }
NWMethod:
enumNWMethod{ GET, POST, DELETE, PUT } //使用:NWMethodValues[NWMethod.POST] constNWMethodValues={ 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'; classDioManager{ staticfinalDioManager_shared=DioManager._internal(); factoryDioManager()=>_shared; Diodio; DioManager._internal(){ if(dio==null){ BaseOptionsoptions=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”:[]}这两种数据是要分开两个请求方法的:
//请求,返回参数为T //method:请求方法,NWMethod.POST等 //path:请求地址 //params:请求参数 //success:请求成功回调 //error:请求失败回调 Futurerequest(NWMethodmethod,Stringpath,{Mapparams,Function(T)success,Function(ErrorEntity)error})async{ try{ Responseresponse=awaitdio.request(path,queryParameters:params,options:Options(method:NWMethodValues[method])); if(response!=null){ BaseEntityentity=BaseEntity .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:"未知错误")); } }onDioErrorcatch(e){ error(createErrorEntity(e)); } } //请求,返回参数为List //method:请求方法,NWMethod.POST等 //path:请求地址 //params:请求参数 //success:请求成功回调 //error:请求失败回调 FuturerequestList (NWMethodmethod,Stringpath,{Mapparams,Function(List)success,Function(ErrorEntity)error})async{ try{ Responseresponse=awaitdio.request(path,queryParameters:params,options:Options(method:NWMethodValues[method])); if(response!=null){ BaseListEntityentity=BaseListEntity .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:"未知错误")); } }onDioErrorcatch(e){ error(createErrorEntity(e)); } }
提取请求错误处理方法createErrorEntity:
//错误信息 ErrorEntitycreateErrorEntity(DioErrorerror){ switch(error.type){ caseDioErrorType.CANCEL:{ returnErrorEntity(code:-1,message:"请求取消"); } break; caseDioErrorType.CONNECT_TIMEOUT:{ returnErrorEntity(code:-1,message:"连接超时"); } break; caseDioErrorType.SEND_TIMEOUT:{ returnErrorEntity(code:-1,message:"请求超时"); } break; caseDioErrorType.RECEIVE_TIMEOUT:{ returnErrorEntity(code:-1,message:"响应超时"); } break; caseDioErrorType.RESPONSE:{ try{ interrCode=error.response.statusCode; StringerrMsg=error.response.statusMessage; returnErrorEntity(code:errCode,message:errMsg); //switch(errCode){ //case400:{ //returnErrorEntity(code:errCode,message:"请求语法错误"); //} //break; //case403:{ //returnErrorEntity(code:errCode,message:"服务器拒绝执行"); //} //break; //case404:{ //returnErrorEntity(code:errCode,message:"无法连接服务器"); //} //break; //case405:{ //returnErrorEntity(code:errCode,message:"请求方法被禁止"); //} //break; //case500:{ //returnErrorEntity(code:errCode,message:"服务器内部错误"); //} //break; //case502:{ //returnErrorEntity(code:errCode,message:"无效的请求"); //} //break; //case503:{ //returnErrorEntity(code:errCode,message:"服务器挂了"); //} //break; //case505:{ //returnErrorEntity(code:errCode,message:"不支持HTTP协议请求"); //} //break; //default:{ //returnErrorEntity(code:errCode,message:"未知错误"); //} //} }onExceptioncatch(_){ returnErrorEntity(code:-1,message:"未知错误"); } } break; default:{ returnErrorEntity(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'; classDioManager{ staticfinalDioManager_shared=DioManager._internal(); factoryDioManager()=>_shared; Diodio; DioManager._internal(){ if(dio==null){ BaseOptionsoptions=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:请求失败回调 Futurerequest(NWMethodmethod,Stringpath,{Mapparams,Function(T)success,Function(ErrorEntity)error})async{ try{ Responseresponse=awaitdio.request(path,queryParameters:params,options:Options(method:NWMethodValues[method])); if(response!=null){ BaseEntityentity=BaseEntity .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:"未知错误")); } }onDioErrorcatch(e){ error(createErrorEntity(e)); } } //请求,返回参数为List //method:请求方法,NWMethod.POST等 //path:请求地址 //params:请求参数 //success:请求成功回调 //error:请求失败回调 FuturerequestList (NWMethodmethod,Stringpath,{Mapparams,Function(List )success,Function(ErrorEntity)error})async{ try{ Responseresponse=awaitdio.request(path,queryParameters:params,options:Options(method:NWMethodValues[method])); if(response!=null){ BaseListEntityentity=BaseListEntity .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:"未知错误")); } }onDioErrorcatch(e){ error(createErrorEntity(e)); } } //错误信息 ErrorEntitycreateErrorEntity(DioErrorerror){ switch(error.type){ caseDioErrorType.CANCEL:{ returnErrorEntity(code:-1,message:"请求取消"); } break; caseDioErrorType.CONNECT_TIMEOUT:{ returnErrorEntity(code:-1,message:"连接超时"); } break; caseDioErrorType.SEND_TIMEOUT:{ returnErrorEntity(code:-1,message:"请求超时"); } break; caseDioErrorType.RECEIVE_TIMEOUT:{ returnErrorEntity(code:-1,message:"响应超时"); } break; caseDioErrorType.RESPONSE:{ try{ interrCode=error.response.statusCode; StringerrMsg=error.response.statusMessage; returnErrorEntity(code:"$errCode",message:errMsg); //switch(errCode){ //case400:{ //returnErrorEntity(code:errCode,message:"请求语法错误"); //} //break; //case403:{ //returnErrorEntity(code:errCode,message:"服务器拒绝执行"); //} //break; //case404:{ //returnErrorEntity(code:errCode,message:"无法连接服务器"); //} //break; //case405:{ //returnErrorEntity(code:errCode,message:"请求方法被禁止"); //} //break; //case500:{ //returnErrorEntity(code:errCode,message:"服务器内部错误"); //} //break; //case502:{ //returnErrorEntity(code:errCode,message:"无效的请求"); //} //break; //case503:{ //returnErrorEntity(code:errCode,message:"服务器挂了"); //} //break; //case505:{ //returnErrorEntity(code:errCode,message:"不支持HTTP协议请求"); //} //break; //default:{ //returnErrorEntity(code:errCode,message:"未知错误"); //} //} }onExceptioncatch(_){ returnErrorEntity(code:-1,message:"未知错误"); } } break; default:{ returnErrorEntity(code:-1,message:error.message); } } } }
使用:
//返回LoginEntity DioManager().request( NWMethod.POST, NWApi.loginPath, params:{"account":"421789838@qq.com","password":"123456"}, success:(data){ print("successdata=$data"}); },error:(error){ print("errorcode=${error.code},massage=${error.message}"); } ); //返回List DioManager().requestList ( NWMethod.POST, NWApi.queryListJsonPath, params:{"account":"421789838@qq.com","password":"123456"}, success:(data){ print("successdata=$data"}); },error:(error){ print("errorcode=${error.code},massage=${error.message}"); } );
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。