downloadMediaFromUrl method

Future<void> downloadMediaFromUrl({
  1. required String fileName,
  2. required String mediaType,
  3. required String url,
  4. required void onProgressUpdate(
    1. int,
    2. int
    ),
  5. required void onDioException(),
})

Implementation

Future<void> downloadMediaFromUrl({
  required String fileName,
  required String mediaType,
  required String url,
  required void Function(int, int) onProgressUpdate,
  required void Function() onDioException,
}) async {
  CancelToken cancelToken = CancelToken();
  final dio = Dio();
  Directory tempDir;

  if (Platform.isIOS) {
    tempDir = await getApplicationDocumentsDirectory();
  } else {
    tempDir = Directory('/storage/emulated/0/Download');
  }

  String savePath = "${tempDir.path}/$fileName.$mediaType";

  for (int i = 0; i < 100; i++) {
    bool exists = await File(savePath).exists();
    if (exists) {
      savePath = "${tempDir.path}/$fileName(${i + 1}).$mediaType";
    } else {
      break;
    }
  }

  LoadingUtils.hideLoader();

  try {
    await dio.download(
      url,
      savePath,
      cancelToken: cancelToken,
      onReceiveProgress: onProgressUpdate,
    );
    // await OpenFile.open(savePath);
  } on DioException catch (e) {
    onDioException();
    ExceptionHandler.handleError(error: e, path: '');
  }
}