request<T> method

Future<IResponse<T>> request<T>(
  1. String apiPath,
  2. EntityGetter fromJsonMethod, {
  3. Map<String, dynamic>? params,
  4. Options? options,
  5. CancelToken? cancelToken,
  6. Method? method = Method.post,
})

发起网络请求

Implementation

Future<IResponse<T>> request<T>(
    String apiPath,
    EntityGetter fromJsonMethod, {
      Map<String, dynamic>? params,
      Options? options,
      CancelToken? cancelToken,
      Method? method = Method.post,
    }) async {
  Response? response;
  try {
    switch (method) {
      case Method.get:
        response = await _dio.get(
          apiPath,
          queryParameters: params,
          cancelToken: cancelToken,
          options: options ?? Options(),
        );
        break;

      case Method.post:
        response = await _dio.post(
          apiPath,
          data: params,
          cancelToken: cancelToken,
          options: options ?? Options(),
        );
        break;

      default:
        throw Exception(['请求方法未实现']);
    }
    return _parseResponse(response, fromJsonMethod);
  } on DioException catch (dioException) {
    // dio描述请求失败时的异常信息
    ApiException exception =
        _paraseDioExceptionResponse(dioException.response) ??
            ApiException.dioError(dioException);
    return Future.value(IResponse.exception(exception));
  } catch (e) {
    // 其他错误,如Json解析异常
    return Future.value(
        IResponse.exception(ApiException.unknowError(e.toString())));
  }
}