downloadFile method

Stream<DownloadProgress> downloadFile({
  1. required String url,
  2. required String filename,
})

Implementation

Stream<DownloadProgress> downloadFile({
  required String url,
  required String filename,
}) async* {
  final cancelToken = CancelToken();
  _cancelTokens[url] = cancelToken;

  yield DownloadProgress(state: DownloadState.downloading, progress: 0);

  try {
    final filePath = await _getDownloadPath(filename);
    debugPrint('📥 Downloading to: $filePath');

    await _dio.download(
      url,
      filePath,
      cancelToken: cancelToken,
      onReceiveProgress: (received, total) {
        if (total != -1) {
          final progress = received / total;
          debugPrint('📥 Progress: ${(progress * 100).toStringAsFixed(1)}%');
        }
      },
    );

    yield DownloadProgress(
      state: DownloadState.completed,
      progress: 1.0,
      filePath: filePath,
    );
  } on DioException catch (e) {
    if (e.type == DioExceptionType.cancel) {
      yield DownloadProgress(
        state: DownloadState.idle,
        error: 'Download cancelled',
      );
    } else {
      yield DownloadProgress(
        state: DownloadState.failed,
        error: e.message ?? 'Download failed',
      );
    }
  } catch (e) {
    yield DownloadProgress(state: DownloadState.failed, error: e.toString());
  } finally {
    _cancelTokens.remove(url);
  }
}