写点什么

Flutter Dio 二次封装,Android 开发还不会这些

用户头像
Android架构
关注
发布于: 13 小时前

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"};

下面就可以进行正式的封装了:

第一步是创建 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, “message”: “”, “data”: {}} 和 {“code”: 0, “message”: “”, “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, 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: "未知错误"));}} 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: "无法连接服务器");//


《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
浏览器打开:qq.cn.hn/FTe 免费领取
复制代码


}// 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,contentType: Headers.jsonContentType,responseType: ResponseType.json,receiveDataWhenStatusError: false,connectTimeout: 30000,receiveTimeout: 3000,);dio = Dio(options);}}


// 请求,返回参数为 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, 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: "未知错误"));}} 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.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: "服务器挂了");

用户头像

Android架构

关注

还未添加个人签名 2021.10.31 加入

还未添加个人简介

评论

发布
暂无评论
Flutter Dio二次封装,Android开发还不会这些