downloadFile method

Future<void> downloadFile({
  1. required String downloadFileUrl,
  2. void onProgress(
    1. double progress
    )?,
  3. void onSuccess(
    1. String filePath
    )?,
  4. void onError(
    1. String error
    )?,
  5. String? downloadFileName,
})

Implementation

Future<void> downloadFile({
  required String downloadFileUrl,
  void Function(double progress)? onProgress,
  void Function(String filePath)? onSuccess,
  void Function(String error)? onError,
  String? downloadFileName,
}) async {
  try {
    Directory? directory = await getExternalStorageDirectory();
    if (directory == null) return;

    String savePath =
        "${directory.path}/${downloadFileName ?? "downloadApk"}.apk";
    Response response = await _dio.download(
      downloadFileUrl,
      savePath,
      onReceiveProgress: (count, total) {
        if (total > 0) {
          double progress = count / total;
          if (onProgress != null) {
            onProgress(progress);
          }
        }
      },
    );
    if (response.statusCode == 200) {
      if (onSuccess != null) {
        onSuccess(savePath);
      }
    } else {
      if (onError != null) {
        onError("Unable to download the file");
      }
    }
  } on DioException catch (e, sc) {
    log(e.toString(), stackTrace: sc);
    String error = _handleDioException(e);
    if (onError != null) {
      onError(error);
    }
  } catch (e, sc) {
    log(e.toString(), stackTrace: sc);
    if (onError != null) {
      onError("Error Occurred while downloading the file");
    }
  }
}