downloadFile method

Future downloadFile({
  1. BuildContext? context,
  2. String? url,
  3. String? downloadFolder,
  4. StorageLocation downloadLocation = StorageLocation.externalStorage,
  5. Function? onStart,
  6. Function? onProgress,
  7. Function? onFinish,
  8. Function? onError,
})

Implementation

Future downloadFile({
  BuildContext? context,
  String? url,
  String? downloadFolder,
  StorageLocation downloadLocation = StorageLocation.externalStorage,
  Function? onStart,
  Function? onProgress,
  Function? onFinish,
  Function? onError,
}) async {
  String baseLocation;
  String? fileName = url?.substring(url.lastIndexOf("/") + 1);
  if (downloadLocation == StorageLocation.externalStorage)
    baseLocation = await Storage().getDownloadFolderPath();
  else {
    final Directory appDir = await getApplicationDocumentsDirectory();
    baseLocation = appDir.path;
  }

  String? fullPath = downloadFolder == null
      ? "$baseLocation/" + fileName!
      : "$baseLocation/$downloadFolder/" + fileName!;

  if (context != null) {
    pdlg = ProgressDialog(context,
        type: ProgressDialogType.download, isDismissible: true);
    pdlg!.update(message: 'Downloading ($fileName)...');
  }

  try {
    if (onStart == null) {
      if (pdlg != null) pdlg!.show();
    } else
      onStart();

    var dio = Dio();

    var ret = await Storage().requestPermission();
    if (ret) {
      Response response = await dio.download(
        url!,
        fullPath,
        onReceiveProgress: (int count, int total) {
          if (total != -1) {
            double downloaded = (count / total * 100);

            if (onProgress == null) if (pdlg != null)
              pdlg!.update(
                  progress: downloaded.roundToDouble(), maxProgress: 100);
            else
              onProgress!(downloaded);

            print(downloaded.toString() + "%");
            if (downloaded.toString() == '100.0') {
              if (onFinish == null) {
                if (pdlg!.isShowing()) pdlg!.hide();
              } else {
                if (pdlg!.isShowing()) pdlg!.hide();
                onFinish();
              }
            }
          }
        },
//Received data with List<int>
        options: Options(
            responseType: ResponseType.bytes,
            followRedirects: false,
            validateStatus: (status) {
              return status! < 500;
            }),
      );
      print(response.headers);
    }
  } catch (e) {
    print('Error:' + e.toString());
    if (onError == null) {
      if (pdlg!.isShowing()) pdlg!.hide();
    } else {
      if (pdlg!.isShowing()) pdlg!.hide();
      onError(e);
    }
  }
}