download method

Future<File> download(
  1. String url,
  2. String filename, {
  3. ProgressCallback? onProgress,
})

Download file to documents, reports progress. If file exists, will try to resume.

Implementation

Future<File> download(String url, String filename,
    {ProgressCallback? onProgress}) async {
  final file = await _localFile(filename);
  int downloadedBytes = 0;
  if (await file.exists()) {
    downloadedBytes = await file.length();
  }

  final headers = <String, String>{};
  if (downloadedBytes > 0) {
    headers['range'] = 'bytes=$downloadedBytes-';
  }

  final response = await _dio.get<ResponseBody>(
    url,
    options: Options(
      responseType: ResponseType.stream,
      headers: headers,
    ),
  );

  final total = response.headers.value('content-length') != null
      ? int.parse(response.headers.value('content-length')!) + downloadedBytes
      : -1;

  final raf = file.openSync(mode: FileMode.append);
  final stream = response.data!.stream;
  int received = downloadedBytes;

  await for (final chunk in stream) {
    raf.writeFromSync(chunk);
    received += chunk.length;
    if (onProgress != null && total > 0) onProgress(received, total);
  }
  await raf.close();

  return file;
}