欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Flutter Dio二次封装的实现

程序员文章站 2022-06-17 14:23:06
目录: diomanager:dio辅助类nwmethod:请求方法,get、post等 nwapi:大家都知道 entityfactory:json转换辅助工厂...

目录:

  • diomanager:dio辅助类nwmethod:请求方法,get、post等
  • nwapi:大家都知道
  • entityfactory:json转换辅助工厂,把json转为t
  • baseentity<t>:数据基类,返回的参数为 {“code”: 0, “message”: “”, “data”: {}}
  • baselistentity<t>:数据基类2,返回的参数为 {“code”: 0, “message”: “”, “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.message, 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"],
   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"
};

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

第一步是创建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: "无法连接服务器");
//      }
//      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: "服务器挂了");
//      }
//      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);
   }
  }
 }
}

使用:

// 返回 loginentity
diomanager().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}");
 }
);

// 返回 list
diomanager().requestlist<loginentity>(
 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}");
 }
);

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