requestAsync method

Future<ResponseModal> requestAsync({
  1. required ApiMethod method,
  2. required String url,
  3. dynamic requestData,
  4. Map<String, dynamic>? headers,
  5. Map<String, dynamic>? queryParameters,
  6. bool useWithoutToken = false,
  7. bool cacheResponse = false,
  8. Duration cacheDuration = const Duration(minutes: 30),
  9. bool forceOffline = false,
  10. CancelToken? cancelToken,
  11. void onSendProgress(
    1. int sent,
    2. int total
    )?,
  12. void onReceiveProgress(
    1. int received,
    2. int total
    )?,
  13. void onProgressPercentage(
    1. double progress
    )?,
})

Implementation

Future<ResponseModal> requestAsync({
  required ApiMethod method,
  required String url,
  dynamic requestData,
  Map<String, dynamic>? headers,
  Map<String, dynamic>? queryParameters,
  bool useWithoutToken = false,
  bool cacheResponse = false,
  Duration cacheDuration = const Duration(minutes: 30),
  bool forceOffline = false,
  CancelToken? cancelToken,
  void Function(int sent, int total)? onSendProgress,
  void Function(int received, int total)? onReceiveProgress,
  void Function(double progress)? onProgressPercentage,
}) {
  final completer = Completer<ResponseModal>();
  final requestCancelToken = cancelToken ?? CancelToken();

  // Handle progress updates
  void Function(int, int)? wrappedOnSendProgress;
  void Function(int, int)? wrappedOnReceiveProgress;

  if (onSendProgress != null || onProgressPercentage != null) {
    wrappedOnSendProgress = (sent, total) {
      onSendProgress?.call(sent, total);
      if (total > 0) {
        final percentage = (sent / total) * 100;
        onProgressPercentage?.call(percentage);
      }
    };
  }

  if (onReceiveProgress != null || onProgressPercentage != null) {
    wrappedOnReceiveProgress = (received, total) {
      onReceiveProgress?.call(received, total);
      if (total > 0) {
        final percentage = (received / total) * 100;
        onProgressPercentage?.call(percentage);
      }
    };
  }

  // Start the request
  request(
    method: method,
    url: url,
    requestData: requestData,
    headers: headers,
    queryParameters: queryParameters,
    useWithoutToken: useWithoutToken,
    cacheResponse: cacheResponse,
    cacheDuration: cacheDuration,
    forceOffline: forceOffline,
    cancelToken: requestCancelToken,
    onSendProgress: wrappedOnSendProgress,
    onReceiveProgress: wrappedOnReceiveProgress,
  ).then((response) {
    if (!completer.isCompleted) {
      completer.complete(response);
    }
  }).catchError((error) {
    if (!completer.isCompleted) {
      completer.completeError(error);
    }
  });

  return completer.future;
}