Flutter Dio二次封裝

頭髮還沒禿發表於2020-01-08

目錄:

  • 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}");
  }
);複製程式碼


相關文章