downloadFile static method
Future<DownloadResult>
downloadFile({
- required String url,
- required String fileName,
- ProgressCallback? onProgress,
- CompleteCallback? onComplete,
- ErrorCallback? onError,
- bool saveToDocuments = false,
- bool allowSelfSignedCertificate = false,
Downloads a file from the given URL and saves it with the specified filename
url - The URL to download from
fileName - The name to save the file as
onProgress - Optional callback for progress updates
onComplete - Optional callback when download completes successfully
onError - Optional callback when download fails
saveToDocuments - Whether to save to Documents directory instead of Downloads (mobile only)
allowSelfSignedCertificate - Whether to allow self-signed SSL certificates (native platforms only)
Returns a Future<DownloadResult> with the download result
Implementation
static Future<DownloadResult> downloadFile({
required String url,
required String fileName,
ProgressCallback? onProgress,
CompleteCallback? onComplete,
ErrorCallback? onError,
bool saveToDocuments = false,
bool allowSelfSignedCertificate = false,
}) async {
try {
// Validate inputs
if (url.isEmpty) {
throw const DownloadException('URL cannot be empty');
}
if (fileName.isEmpty) {
throw const DownloadException('Filename cannot be empty');
}
// Check storage permission for mobile platforms
if (!kIsWeb && (io.Platform.isAndroid || io.Platform.isIOS)) {
final hasPermission = await PermissionUtils.requestStoragePermission();
if (!hasPermission) {
throw PermissionDownloadException(
PermissionUtils.getPermissionErrorMessage(),
url: url,
);
}
}
// Use platform-specific implementation
if (kIsWeb) {
return await _downloadForWeb(
url: url,
fileName: fileName,
onProgress: onProgress,
onComplete: onComplete,
onError: onError,
);
} else {
return await _downloadForNative(
url: url,
fileName: fileName,
onProgress: onProgress,
onComplete: onComplete,
onError: onError,
saveToDocuments: saveToDocuments,
allowSelfSignedCertificate: allowSelfSignedCertificate,
);
}
} catch (e) {
final errorMessage = e.toString();
onError?.call(errorMessage);
return DownloadResult.failure(
url: url,
fileName: fileName,
errorMessage: errorMessage,
);
}
}