downloadAndWaitForBytes static method

Future<DownloadResult> downloadAndWaitForBytes({
  1. required String url,
  2. required String filePath,
  3. int startByte = 0,
  4. int minBytes = minBytesForPlayback,
  5. Map<String, String>? headers,
})

Start downloading and wait until minimum bytes are available. Returns a Future that completes when minBytes are downloaded. Download continues in background after Future completes.

Implementation

static Future<DownloadResult> downloadAndWaitForBytes({
  required String url,
  required String filePath,
  int startByte = 0,
  int minBytes = minBytesForPlayback,
  Map<String, String>? headers,
}) async {
  final completer = Completer<DownloadResult>();
  bool thresholdReached = false;

  final stream = download(
    url: url,
    filePath: filePath,
    startByte: startByte,
    headers: headers,
  );

  late StreamSubscription<DownloadProgress> subscription;
  subscription = stream.listen(
    (progress) {
      if (!thresholdReached) {
        if (progress.downloadedBytes >= minBytes || progress.isComplete) {
          thresholdReached = true;
          completer.complete(DownloadResult(
            downloadedBytes: progress.downloadedBytes,
            isComplete: progress.isComplete,
            subscription: subscription,
          ));
        }
      }
    },
    onError: (e) {
      if (!thresholdReached) {
        thresholdReached = true;
        completer.completeError(e);
      }
    },
    onDone: () {
      if (!thresholdReached) {
        thresholdReached = true;
        completer.complete(DownloadResult(
          downloadedBytes: 0,
          isComplete: true,
          subscription: subscription,
        ));
      }
    },
  );

  return completer.future;
}