downloadFile method
Implementation
Future<dynamic> downloadFile({
required String url,
Function(double progress)? onProgress,
}) async {
try {
// Determine the download directory based on the platform
final Directory? downloadsDir;
if (Platform.isAndroid) {
downloadsDir = Directory("/storage/emulated/0/Download");
} else {
downloadsDir = await getApplicationDocumentsDirectory();
}
// Create a subdirectory for the app's files
final Directory appDir = Directory("${downloadsDir.path}/myApp");
if (!await appDir.exists()) {
await appDir.create(recursive: true);
}
// Generate the file path
final String fileName = url.split('/').last;
final String filePath = "${appDir.path}/$fileName";
// Download file using Dio
await _dio.download(
url,
filePath,
options: Options(
headers: {
"Content-Type": "*/*",
"Accept": "*/*",
},
),
onReceiveProgress: (received, total) {
if (total != -1 && onProgress != null) {
// Calculate and pass progress percentage
onProgress((received / total) * 100);
}
},
);
// Return success response
return filePath;
} catch (e) {
rethrow;
}
}