fetch method

Future<Response<List<int>>> fetch(
  1. String url, {
  2. Map<String, dynamic>? queryParameters,
  3. Options? options,
  4. CancelToken? cancelToken,
  5. ProgressCallback? onReceiveProgress,
  6. CacheOptions? cacheOptions,
})

Fetches raw data from the specified url as a list of bytes.

Useful for retrieving images, files, or other non-JSON data. This method enforces ResponseType.bytes. Any responseType specified in the options parameter will be overridden. Supports caching via cacheOptions or globalCacheOptions.

  • url: The request URL.
  • queryParameters: Optional URL query parameters.
  • options: Dio Options for this specific request (e.g., headers). responseType will be forced to ResponseType.bytes.
  • cancelToken: Optional CancelToken for cancellation.
  • onReceiveProgress: Optional callback for tracking download progress.
  • cacheOptions: Optional CacheOptions specific to this request.

Returns a Future<Response<List<int>>> containing the raw byte data upon success.

Throws a NetworkException subtype on failure.

Implementation

Future<Response<List<int>>> fetch(
  String url, {
  Map<String, dynamic>? queryParameters,
  Options? options,
  CancelToken? cancelToken,
  ProgressCallback? onReceiveProgress,
  CacheOptions? cacheOptions,
}) async {
  try {
    // Start with base options forcing bytes, then merge user options and cache options
    final mergedDioOptions = (options ?? Options()).copyWith(
      responseType: ResponseType.bytes,
    );

    final finalOptions = _mergeDioAndCacheOptions(
      dioOptions: mergedDioOptions, // Ensure ResponseType.bytes is kept
      cacheOptions: cacheOptions ?? globalCacheOptions,
    )?.copyWith(responseType: ResponseType.bytes); // Ensure again after merge

    final Response<List<int>> response = await _dio.get<List<int>>(
      // Specify type argument for clarity
      url,
      queryParameters: queryParameters,
      options: finalOptions, // Use the final merged options
      cancelToken: cancelToken,
      onReceiveProgress: onReceiveProgress,
    );
    return response;
  } on DioException catch (e) {
    // Handle potential DioException where response might not be List<int>
    // _handleDioError already handles the core network issues
    throw _handleDioError(e);
  } catch (e) {
    // Catch other unexpected errors
    throw UnknownNetworkErrorException(
      message: 'Unexpected error during fetch request processing: $e',
      code: NetworkErrorCode.unknownError,
      originalError: e,
    );
  }
}