FlutterDio中怎么實(shí)現(xiàn)二次封裝,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
目前
創(chuàng)新互聯(lián)公司已為超過千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、
雅安服務(wù)器托管、網(wǎng)站托管維護(hù)、企業(yè)網(wǎng)站設(shè)計(jì)、
樂安網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
目錄:
DioManager:Dio輔助類NWMethod:請(qǐng)求方法,get、post等 NWApi:大家都知道 EntityFactory:json轉(zhuǎn)換輔助工廠,把json轉(zhuǎn)為T BaseEntity:數(shù)據(jù)基類,返回的參數(shù)為 {“code”: 0, “message”: “”, “data”: {}} BaseListEntity:數(shù)據(jù)基類2,返回的參數(shù)為 {“code”: 0, “message”: “”, “data”: []} ErrorEntity:請(qǐng)求報(bào)錯(cuò)基類,{“code”: 0, “message”: “”}
EntityFactory:
class EntityFactory { static T generateOBJ(json) { if (json == null) { return null; }//可以在這里加入任何需要并且可以轉(zhuǎn)換的類型,例如下面// else if (T.toString() == "LoginEntity") {// return LoginEntity.fromJson(json) as T;// } else { return json as T; } }}
BaseEntity:
class BaseEntity { 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值需要經(jīng)過工廠轉(zhuǎn)換為我們傳進(jìn)來的類型 data: EntityFactory.generateOBJ(json["data"]), ); }}
BaseListEntity:
class BaseListEntity { int code; String message; List data; BaseListEntity({this.code, this.message, this.data}); factory BaseListEntity.fromJson(json) { List mData = List(); if (json['data'] != null) { //遍歷data并轉(zhuǎn)換為我們傳進(jìn)來的類型 (json['data'] as List).forEach((v) { mData.add(EntityFactory.generateOBJ(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";//接口返回:{"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:
enum NWMethod { GET, POST, DELETE, PUT}//使用:NWMethodValues[NWMethod.POST]const NWMethodValues = { NWMethod.GET: "get", NWMethod.POST: "post", NWMethod.DELETE: "delete", NWMethod.PUT: "put"};
下面就可以進(jìn)行正式的封裝了:
第一步是創(chuàng)建Dio的單例輔助類,并初始化Dio和對(duì)Dio進(jìn)行一些全局的參數(shù)設(shè)置:
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); } }}
第二步對(duì)請(qǐng)求進(jìn)行封裝,在我的想法中 {“code”: 0, “message”: “”, “data”: {}} 和 {“code”: 0, “message”: “”, “data”: []} 這兩種數(shù)據(jù)是要分開兩個(gè)請(qǐng)求方法的:
// 請(qǐng)求,返回參數(shù)為 T // method:請(qǐng)求方法,NWMethod.POST等 // path:請(qǐng)求地址 // params:請(qǐng)求參數(shù) // success:請(qǐng)求成功回調(diào) // error:請(qǐng)求失敗回調(diào) Future request(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.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: "未知錯(cuò)誤")); } } on DioError catch(e) { error(createErrorEntity(e)); } } // 請(qǐng)求,返回參數(shù)為 List // method:請(qǐng)求方法,NWMethod.POST等 // path:請(qǐng)求地址 // params:請(qǐng)求參數(shù) // success:請(qǐng)求成功回調(diào) // error:請(qǐng)求失敗回調(diào) Future requestList(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.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: "未知錯(cuò)誤")); } } on DioError catch(e) { error(createErrorEntity(e)); } }
提取請(qǐng)求錯(cuò)誤處理方法createErrorEntity:
// 錯(cuò)誤信息 ErrorEntity createErrorEntity(DioError error) { switch (error.type) { case DioErrorType.CANCEL:{ return ErrorEntity(code: -1, message: "請(qǐng)求取消"); } break; case DioErrorType.CONNECT_TIMEOUT:{ return ErrorEntity(code: -1, message: "連接超時(shí)"); } break; case DioErrorType.SEND_TIMEOUT:{ return ErrorEntity(code: -1, message: "請(qǐng)求超時(shí)"); } break; case DioErrorType.RECEIVE_TIMEOUT:{ return ErrorEntity(code: -1, message: "響應(yīng)超時(shí)"); } 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: "請(qǐng)求語法錯(cuò)誤");// }// break;// case 403: {// return ErrorEntity(code: errCode, message: "服務(wù)器拒絕執(zhí)行");// }// break;// case 404: {// return ErrorEntity(code: errCode, message: "無法連接服務(wù)器");// }// break;// case 405: {// return ErrorEntity(code: errCode, message: "請(qǐng)求方法被禁止");// }// break;// case 500: {// return ErrorEntity(code: errCode, message: "服務(wù)器內(nèi)部錯(cuò)誤");// }// break;// case 502: {// return ErrorEntity(code: errCode, message: "無效的請(qǐng)求");// }// break;// case 503: {// return ErrorEntity(code: errCode, message: "服務(wù)器掛了");// }// break;// case 505: {// return ErrorEntity(code: errCode, message: "不支持HTTP協(xié)議請(qǐng)求");// }// break;// default: {// return ErrorEntity(code: errCode, message: "未知錯(cuò)誤");// }// } } on Exception catch(_) { return ErrorEntity(code: -1, message: "未知錯(cuò)誤"); } } 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, contentType: Headers.jsonContentType, responseType: ResponseType.json, receiveDataWhenStatusError: false, connectTimeout: 30000, receiveTimeout: 3000, ); dio = Dio(options); } } // 請(qǐng)求,返回參數(shù)為 T // method:請(qǐng)求方法,NWMethod.POST等 // path:請(qǐng)求地址 // params:請(qǐng)求參數(shù) // success:請(qǐng)求成功回調(diào) // error:請(qǐng)求失敗回調(diào) Future request(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.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: "未知錯(cuò)誤")); } } on DioError catch(e) { error(createErrorEntity(e)); } } // 請(qǐng)求,返回參數(shù)為 List // method:請(qǐng)求方法,NWMethod.POST等 // path:請(qǐng)求地址 // params:請(qǐng)求參數(shù) // success:請(qǐng)求成功回調(diào) // error:請(qǐng)求失敗回調(diào) Future requestList(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.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: "未知錯(cuò)誤")); } } on DioError catch(e) { error(createErrorEntity(e)); } } // 錯(cuò)誤信息 ErrorEntity createErrorEntity(DioError error) { switch (error.type) { case DioErrorType.CANCEL:{ return ErrorEntity(code: -1, message: "請(qǐng)求取消"); } break; case DioErrorType.CONNECT_TIMEOUT:{ return ErrorEntity(code: -1, message: "連接超時(shí)"); } break; case DioErrorType.SEND_TIMEOUT:{ return ErrorEntity(code: -1, message: "請(qǐng)求超時(shí)"); } break; case DioErrorType.RECEIVE_TIMEOUT:{ return ErrorEntity(code: -1, message: "響應(yīng)超時(shí)"); } 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: "請(qǐng)求語法錯(cuò)誤");// }// break;// case 403: {// return ErrorEntity(code: errCode, message: "服務(wù)器拒絕執(zhí)行");// }// break;// case 404: {// return ErrorEntity(code: errCode, message: "無法連接服務(wù)器");// }// break;// case 405: {// return ErrorEntity(code: errCode, message: "請(qǐng)求方法被禁止");// }// break;// case 500: {// return ErrorEntity(code: errCode, message: "服務(wù)器內(nèi)部錯(cuò)誤");// }// break;// case 502: {// return ErrorEntity(code: errCode, message: "無效的請(qǐng)求");// }// break;// case 503: {// return ErrorEntity(code: errCode, message: "服務(wù)器掛了");// }// break;// case 505: {// return ErrorEntity(code: errCode, message: "不支持HTTP協(xié)議請(qǐng)求");// }// break;// default: {// return ErrorEntity(code: errCode, message: "未知錯(cuò)誤");// }// } } on Exception catch(_) { return ErrorEntity(code: -1, message: "未知錯(cuò)誤"); } } break; default: { return ErrorEntity(code: -1, message: error.message); } } }}
使用:
// 返回 LoginEntityDioManager().request( 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( 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}"); });
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,的支持。
當(dāng)前文章:FlutterDio中怎么實(shí)現(xiàn)二次封裝-創(chuàng)新互聯(lián)
文章來源:
http://weahome.cn/article/cscodo.html