download method

Future<HTTPResult> download(
  1. String url,
  2. String destinationPath, {
  3. void onProgress(
    1. int downloaded,
    2. int total
    )?,
  4. Duration? timeout,
})

Download file

Implementation

Future<HTTPResult> download(
  String url,
  String destinationPath, {
  void Function(int downloaded, int total)? onProgress,
  Duration? timeout,
}) async {
  try {
    final uri = url.startsWith('http') ? Uri.parse(url) : Uri.parse('$_baseURL$url');

    final client = http.Client();
    try {
      final request = http.Request('GET', uri);
      if (_accessToken != null) {
        request.headers['Authorization'] = 'Bearer $_accessToken';
      }

      final streamedResponse = await client.send(request);

      if (streamedResponse.statusCode >= 200 && streamedResponse.statusCode < 300) {
        final file = await _saveStreamToFile(
          streamedResponse.stream,
          destinationPath,
          streamedResponse.contentLength ?? 0,
          onProgress,
        );

        return HTTPResult.success(
          statusCode: streamedResponse.statusCode,
          body: file,
        );
      } else {
        return HTTPResult(
          isSuccess: false,
          statusCode: streamedResponse.statusCode,
          error: 'Download failed with status ${streamedResponse.statusCode}',
        );
      }
    } finally {
      client.close();
    }
  } catch (e) {
    return HTTPResult.failure(e.toString());
  }
}