download method

Future<Response> download(
  1. String url,
  2. String savePath, {
  3. Map<String, dynamic>? queryParameters,
  4. Options? options,
  5. CancelToken? cancelToken,
  6. ProgressCallback? onReceiveProgress,
  7. bool deleteOnError = true,
})

Downloads a file from the specified url and saves it to savePath.

This method uses Dio.download internally. Caching is not supported or applied for download requests made via this method.

  • url: The file URL to download.
  • savePath: The absolute file path (including filename) where the file will be saved. Ensure the directory exists and the app has write permissions.
  • queryParameters: Optional URL query parameters.
  • options: Dio Options for this specific request (e.g., headers). responseType is ignored.
  • cancelToken: Optional CancelToken for cancellation.
  • onReceiveProgress: Strongly recommended callback for tracking download progress (bytesReceived, totalBytes).
  • deleteOnError: If true, the partially downloaded file will be deleted if an error occurs. Defaults to true.

Returns a standard Future<Response> upon successful download. The response body will typically be null.

Throws a NetworkException subtype on network failures. Throws UnknownNetworkErrorException if a file system error occurs during saving (if not already wrapped in a DioException by Dio).

Implementation

Future<Response> download(
  String url,
  String savePath, {
  Map<String, dynamic>? queryParameters,
  Options? options,
  CancelToken? cancelToken,
  ProgressCallback? onReceiveProgress,
  bool deleteOnError = true,
}) async {
  try {
    final response = await _dio.download(
      url,
      savePath, // The destination file path
      queryParameters: queryParameters,
      options: options, // Pass user options (like headers)
      cancelToken: cancelToken,
      onReceiveProgress: onReceiveProgress,
      deleteOnError: deleteOnError,
    );
    return response;
  } on DioException catch (e) {
    // Handles network errors and potentially some file system errors if Dio wraps them
    throw _handleDioError(e);
  } catch (e) {
    // Catches potential file system errors (e.g., permissions, path not found)
    // if not wrapped by Dio, or other unexpected errors.
    throw UnknownNetworkErrorException(
      message:
          'Unexpected error during download request processing (check network, path, and permissions): $e',
      code: NetworkErrorCode
          .unknownError, // Could refine code if needed, but unknown is safe
      originalError: e,
    );
  }
}