request<T> method

Future<void> request<T>(
  1. Method method,
  2. String path, {
  3. String? baseUrl,
  4. Map<String, dynamic>? params,
  5. Map<String, dynamic>? header,
  6. dynamic data,
  7. ProgressCallback? onSendProgress,
  8. ProgressCallback? onReceiveProgress,
  9. Success? success,
  10. CancelToken? cancelToken,
  11. OnValueCallBack<CancelToken>? cancelTokenCallBack,
  12. Empty? empty,
  13. Error? error,
})

请求,返回参数为 T method:请求方法,NWMethod.GET等 path:请求地址 params:请求参数 success:请求成功回调 error:请求失败回调

Implementation

Future<void> request<T>(Method method, String path,
    {String? baseUrl,
    Map<String, dynamic>? params,
    Map<String, dynamic>? header,
    data,
    ProgressCallback? onSendProgress, // 上传数据进度
    ProgressCallback? onReceiveProgress, // 接受数据进度
    Success? success,
    CancelToken? cancelToken, //可自定义一个取消令牌,也可从回调中获取系统默认取消令牌
    OnValueCallBack<CancelToken>? cancelTokenCallBack, //回调,返回一个取消令牌
    Empty? empty,
    Error? error}) async {
  try {
    var connectivityResult = await (Connectivity().checkConnectivity());

    if (connectivityResult == ConnectivityResult.none) {
      if (error != null) {
        error(ErrorRes(code: -9, message: "网络异常~,请检查您的网络状态!"));
      }
      return;
    }
    _setBaseUrl(baseUrl);
    _changeHeader(header);
    if (headerDelegate != null) {
      headerDelegate!(params);
      updateHeader();
    }

    ///增加一个取消token
    var token = cancelToken ?? CancelToken();
    cancelTokenCallBack?.call(token);

    Response? response = await _dio?.request(
      path,
      queryParameters: params,
      data: data,
      cancelToken: token,
      onSendProgress: onSendProgress,
      onReceiveProgress: onReceiveProgress,
      options: Options(method: methodValues[method]),
    );
    if (response != null) {
      BaseRes entity = BaseRes.fromJson(response.data);
      // 本公司接口的code = 200、0、1 都认为请求成功
      if (entity.code == 200 ||
          entity.code == 0 ||
          entity.code == 1 && entity.data != null && entity.data != '') {
        success?.call(entity.data);
      } else if (entity.code == 200 || entity.code == 0 || entity.code == 1) {
        empty?.call();
      } else {
        error?.call(ErrorRes(code: entity.code, message: entity.message));
      }
    } else {
      error?.call(ErrorRes(code: -1, message: "未知错误"));
    }
  } on DioError catch (e) {
    error?.call(createErrorEntity(e));
  }
}