downloadFile method
This function used for downlaod file from url and use locally for serveral purposes url is http location where file avaiblable for downlaod Progress is callback tell about download progress Storage directory tell where to download file currruntly avaiable for android devices only
Implementation
Future<File?> downloadFile(
{String? url,
Function(String)? progress,
pp.StorageDirectory? storageDirectory}) async {
Dio dio = new Dio();
if (url == null) {
"Download Location cant be null".printerror;
return null;
}
List<Directory>? tempDir =
await pp.getExternalStorageDirectories(type: storageDirectory);
String? urlFileType = getUrlFileExtension(url);
String fullPath = tempDir!.first.path + "/${Uuid().v4()}${urlFileType}";
fullPath.printinfo;
File file = new File("");
try {
Response response = await dio.get(
url,
onReceiveProgress: (received, total) {
if (total != -1) {
if (progress != null)
progress((received / total * 100).toStringAsFixed(0));
}
},
//Received data with List<int>
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
validateStatus: (status) {
return status! < 500;
}),
);
print(response.headers);
file = File(fullPath);
var raf = file.openSync(mode: FileMode.write);
// response.data is List<int> type
raf.writeFromSync(response.data);
await raf.close();
} catch (e) {
print(e);
return null;
}
return file;
}