Flutter Dio网络网络请求简单封装

参考资源:https://github.com/po1arbear/Flutter-Net/blob/master/lib/http_manager.dart 

dio版本:dio: ^3.0.9

Dio工具类完整代码

import 'package:dio/dio.dart';
import '../api/apis.dart';
import 'result_data.dart';


/**
 * @Author: xw
 * @Description: DioUtil.
 * @Date: 2020/4/9
 */


class DioUtil {
  static DioUtil _instance = DioUtil._internal();
  Dio _dio;

  factory DioUtil() => _instance;

  ///通用全局单例,第一次使用时初始化
  DioUtil._internal({String baseUrl}) {
    if (null == _dio) {
      _dio = new Dio(
          new BaseOptions(baseUrl: Apis.BaseURL, connectTimeout: 15000));
    }
  }

  static DioUtil getInstance({String baseUrl}) {
    if (baseUrl == null) {
      return _instance._normal();
    } else {
      return _instance._baseUrl(baseUrl);
    }
  }

  //用于指定特定域名,比如cdn和kline首次的http请求
  DioUtil _baseUrl(String baseUrl) {
    if (_dio != null) {
      _dio.options.baseUrl = baseUrl;
    }
    return this;
  }

  //一般请求,默认域名
  DioUtil _normal() {
    if (_dio != null) {
      if (_dio.options.baseUrl != Apis.BaseURL) {
        _dio.options.baseUrl = Apis.BaseURL;
      }
    }
    return this;
  }

  ///通用的GET请求
  get(api, params, {noTip = false}) async {
    Response response;
    try {
      response = await _dio.get(api, queryParameters: params);
    } on DioError catch (e) {
      return resultError(e);
    }

    if (response.data is DioError) {
      return resultError(response.data['code']);
    }

    return ResultData(response.data, true, 200);
  }

  ///通用的POST请求
  post(api, params, {noTip = false}) async {
    Response response;
    try {
      response = await _dio.post(api, data: params);
    } on DioError catch (e) {
      return resultError(e);
    }

    if (response.data is DioError) {
      return resultError(response.data['code']);
    }

    return ResultData(response.data, true, 200);
  }

  ResultData resultError(DioError error) {
    switch (error.type) {
      case DioErrorType.CANCEL:
        return new ResultData("请求取消", false, -1);
        break;
      case DioErrorType.CONNECT_TIMEOUT:
        return new ResultData("连接超时", false, -1);
        break;
      case DioErrorType.SEND_TIMEOUT:
        return new ResultData("请求超时", false, -1);
        break;
      case DioErrorType.RECEIVE_TIMEOUT:
        return new ResultData("响应超时", false, -1);
        break;
      case DioErrorType.RESPONSE:
        try {
          int errCode = error.response.statusCode;
          String errMsg = error.response.statusMessage;
          switch (errCode) {
            case 400:
              return new ResultData(
                  "\"errCode\":505,\"message\":\"请求语法错误\"", false, errCode);
              break;
            case 403:
              return new ResultData(
                  "\"errCode\":505,\"message\":\"服务器拒绝执行\"", false, errCode);
              break;
            case 404:
              return new ResultData(
                  "\"errCode\":505,\"message\":\"无法连接服务器\"", false, errCode);
              break;
            case 405:
              return new ResultData(
                  "\"errCode\":505,\"message\":\"请求方法被禁止\"", false, errCode);
              break;
            case 500:
              return new ResultData(
                  "\"errCode\":500,\"message\":\"服务器内部错误\"", false, errCode);
              break;
            case 502:
              return new ResultData(
                  "\"errCode\":502,\"message\":\"无效的请求\"", false, errCode);
              break;
            case 503:
              return new ResultData(
                  "\"errCode\":503,\"message\":\"服务器挂了\"", false, errCode);
              break;
            case 505:
              return new ResultData(
                  "\"errCode\":505,\"message\":\"不支持HTTP协议请求\"", false, errCode);
              break;
            default:
              return new ResultData(
                  "\"errCode\":$errCode,\"message\":$errMsg", false, errCode);
          }
        } on Exception catch (err) {
          return new ResultData("未知错误:$err", false, -1);
        }
        break;
      default:
        if (error.message.contains("Network is unreachable")) {
          return new ResultData("网络错误", false, -1);
        } else {
          return new ResultData(error.message, false, -1);
        }
    }
  }

}

ResultData

class ResultData {
  var data;
  bool isSuccess;
  int code;
  var headers;

  ResultData(this.data, this.isSuccess, this.code, {this.headers});
}

简单使用

ResultData res = await DioUtil.getInstance().get(Apis.FollowURL, null);
    if(res.isSuccess){
        _dioType = 1;
        String data = res.data.toString();
        if (null != data && data.isNotEmpty && data != "[]") {
          _followType = 1;
        } else {
          _followType = 0;
        }
    }else{
      _dioType = 0;
    }
    print("cxy--------------------------"+res.data.toString());
    notifyListeners();

 

你可能感兴趣的:(flutter)