handleDownloadStream function

Future<void> handleDownloadStream(
  1. Stream<StreamedResponse> resp, {
  2. required File file,
  3. Function? onDownloading,
  4. Function? onDownloaded,
})

Implementation

Future<void> handleDownloadStream(
  Stream<StreamedResponse> resp, {
  required File file,
  Function? onDownloading,
  Function? onDownloaded,
}) async {
  List<List<int>> chunks = [];

  onDownloading?.call();

  resp.listen((StreamedResponse r) {
    r.stream.listen((List<int> chunk) {
      if (r.contentLength == null) {
        if (kDebugMode) {
          print("Error");
        }
      }

      chunks.add(chunk);
    }, onDone: () async {
      final Uint8List bytes = Uint8List(r.contentLength ?? 0);
      int offset = 0;
      for (List<int> chunk in chunks) {
        bytes.setRange(offset, offset + chunk.length, chunk);
        offset += chunk.length;
      }
      await file.writeAsBytes(bytes);
      OpenFile.open(file.absolute.path);
      if (onDownloaded != null) {
        onDownloaded();
      }
    });
  });
}