fileDownload method

Future<String> fileDownload(
  1. String url, {
  2. required String path,
  3. void onDownloadProgress(
    1. int bytes,
    2. int totalBytes
    )?,
})

donload file with proggres

Implementation

Future<String> fileDownload(
  String url, {
  required String path,
  void Function(int bytes, int totalBytes)? onDownloadProgress,
}) async {
  final httpClient = HttpClient();
  final request = await httpClient.getUrl(Uri.parse(url));
  request.headers.add(
    HttpHeaders.contentTypeHeader,
    "application/octet-stream",
  );
  var httpResponse = await request.close();
  int byteCount = 0;
  int totalBytes = httpResponse.contentLength;
  File file = File(path);
  var raf = file.openSync(mode: FileMode.write);
  Completer completer = Completer<String>();
  httpResponse.listen(
    (data) {
      byteCount += data.length;
      raf.writeFromSync(data);
      if (onDownloadProgress != null) {
        onDownloadProgress(byteCount, totalBytes);
      }
    },
    onDone: () {
      raf.closeSync();
      completer.complete(file.path);
    },
    onError: (e) {
      raf.closeSync();
      file.deleteSync();
      completer.completeError(e);
    },
    cancelOnError: true,
  );
  return await completer.future;
}