downloadWithProgress method
Stream<int>
downloadWithProgress(
- String url,
- String targetPath, {
- String? token,
- int maxRetries = 10,
- CancelToken? cancelToken,
override
Downloads a file with progress tracking
Returns a stream of progress percentages (0-100)
Parameters:
url
: Source URLtargetPath
: Destination pathtoken
: Optional auth tokenmaxRetries
: Max retry attempts for transient errors (default: 10) Note: Auth errors (401/403/404) fail after 1 attempt regardless of this valuecancelToken
: Optional token for cancellation
Throws:
- DownloadCancelledException if cancelled via cancelToken
Example:
final cancelToken = CancelToken();
await for (final progress in downloader.downloadWithProgress(..., cancelToken: cancelToken)) {
print('Progress: $progress%');
}
// Cancel from elsewhere: cancelToken.cancel('User cancelled');
Implementation
@override
Stream<int> downloadWithProgress(
String url,
String targetPath, {
String? token,
int maxRetries = 10,
CancelToken? cancelToken,
}) async* {
// Check cancellation before starting
cancelToken?.throwIfCancelled();
if (token == null) {
// PUBLIC PATH: Direct URL registration
try {
final uri = Uri.tryParse(url);
if (uri == null || (!uri.isScheme('HTTP') && !uri.isScheme('HTTPS'))) {
throw ArgumentError('Invalid URL: $url. Must be HTTP or HTTPS.');
}
debugPrint('WebDownloadService: Registering public URL for $targetPath');
// Register direct URL
_fileSystem.registerUrl(targetPath, url);
// Simulate progress with cancellation checks
const totalSteps = 20;
const stepDelay = Duration(milliseconds: 50);
for (int i = 0; i <= totalSteps; i++) {
// Check cancellation on each step
cancelToken?.throwIfCancelled();
final progress = (i * 100 ~/ totalSteps).clamp(0, 100);
yield progress;
if (i < totalSteps) {
await Future.delayed(stepDelay);
}
}
debugPrint('WebDownloadService: Completed registration for $targetPath');
} catch (e) {
debugPrint('WebDownloadService: Registration failed for $targetPath: $e');
if (e is ArgumentError || e is DownloadCancelledException) {
rethrow;
}
throw DownloadException(
DownloadError.unknown('Failed to register model URL: $e'),
);
}
} else {
// PRIVATE PATH: Fetch with auth
debugPrint('WebDownloadService: Starting authenticated download for $targetPath');
yield* _downloadWithAuth(url, targetPath, token, cancelToken);
}
}