downloadFile method

  1. @override
Future<void> downloadFile({
  1. required DownloadItem item,
  2. required dynamic onProgress(
    1. int,
    2. int
    ),
})
override

Implementation

@override
Future<void> downloadFile({
  required DownloadItem item,
  required Function(int, int) onProgress,
}) async {
  item.cancelToken = CancelToken();

  try {
    final res = await dio.get(
      item.fileUrl,
      options: Options(responseType: ResponseType.bytes),
      onReceiveProgress: (rec, total) {
        onProgress(rec, total);
      },
      cancelToken: item.cancelToken,
    );

    final data = Uint8List.fromList(res.data as List<int>).buffer.toJS;
    final blob = web.Blob([data].toJS);
    final url = web.URL.createObjectURL(blob);

    final anchor = web.HTMLAnchorElement()
      ..href = url
      ..setAttribute('download', item.fileName);
    web.document.body!.appendChild(anchor);
    anchor.click();
    anchor.remove();

    web.URL.revokeObjectURL(url);
    print('Download Complete');
  } on DioException catch (e) {
    if (CancelToken.isCancel(e)) {
      print('Download Cancelled by user.');
    } else {
      print('Download Failed: ${e.message}');
    }
    rethrow;
  }
}