request method

Future request(
  1. String path, {
  2. String method = "GET",
  3. Map<String, dynamic>? params,
  4. dynamic data,
  5. Options? options,
  6. CancelToken? cancelToken,
  7. bool refresh = false,
  8. bool noCache = true,
  9. String? cacheKey,
  10. bool needResponse = true,
  11. bool cacheDisk = false,
  12. bool isLoading = false,
  13. bool isCustomResponse = false,
  14. FailFunction? fail,
})

Implementation

Future request(String path,
    {String method = "GET",
    Map<String, dynamic>? params,
    data,
    Options? options,
    CancelToken? cancelToken,
    bool refresh = false,
    bool noCache = true,
    String? cacheKey,
    bool needResponse = true,
    bool cacheDisk = false,
    bool isLoading = false,
    bool isCustomResponse = false,
    FailFunction? fail}) async {
  if (isLoading) {
    EasyLoading.show();
  }

  Options requestOptions = options ?? Options();
  requestOptions = requestOptions.copyWith(
    method: method,
    extra: {
      "refresh": refresh,
      "noCache": noCache,
      "cacheKey": cacheKey,
      "cacheDisk": cacheDisk,
    },
  );

  Response response;
  CancelToken dioCancelToken = createDioCancelToken(cancelToken);

  if (!path.startsWith("http")) {
    var instance = Get.find<IDemonConfig>();
    if (path.startsWith("/")) {
      path = instance.getApiRoot() + path;
    } else {
      path = instance.getApiRoot() + "/" + path;
    }
  }
  response = await dio
      .request(
    path,
    data: data,
    queryParameters: params,
    options: requestOptions,
    cancelToken: dioCancelToken,
  )
      .onError((error, stackTrace) {
    if (fail == null) {
      EasyLoading.showToast('网络错误');
    } else {
      fail(error, stackTrace);
    }

    return Future.error(() {});
  }).whenComplete(() {
    if (isLoading) {
      EasyLoading.dismiss();
    }
  });

  ///debugPrint('Response==>:${response.data}');
  pendingRequest.remove(dioCancelToken);

  if (!needResponse) {
    return "";
  }

  ApiResponse result;

  if (response.data != null && !isCustomResponse) {
    result = ApiResponse.fromJson(response.data);
  } else {
    return response.data;
  }

  if (result.code == 1) {
    return result.data;
  }
  if (result.code == 401) {
    final instance = Get.find<IDemonConfig>();
    instance.makeLogout();
    return Future.error(() {});
  }
  if (result.code != null) {
    EasyLoading.showToast(result.message ?? "服务器繁忙");
    return Future.error(() {});
  }

  return response.data;
}