dart下载进度:http

时间:2019-06-17 20:58:08

标签: flutter dart dart-http

我正在尝试为下载文件制作进度条指示器,但是如果我向StreamedResponse添加一个侦听器,则管道工作正常,但并不能结束其未来。

final client = new http.Client();
http.StreamedResponse response = await client.send(http.Request("GET", Uri.parse('someurl')));

var received = 0;
var length = response.contentLength;

//if I remove this listener, the await below gets completed
var listen = response.stream.listen((List<int> bytes) {
  received += bytes.length;
  print("${(received / length) * 100} %");
});

var sink = downloadFile.openWrite();
await response.stream.pipe(sink);
listen.cancel();
sink.close();

github上,他们已经告知某人它应该可以工作,但在StreamedResponse docs上,则保留了This should always be a single-subscription stream.。因此,添加侦听器以计算百分比似乎在某种程度上使StreamedResponse管道出错。关于如何使它起作用的任何想法吗?

1 个答案:

答案 0 :(得分:0)

@pskink的评论让我对这种解决方案有效,该解决方案适用于您使用的每种sink类型。

  var length = response.contentLength;
  var received = 0;
  var sink = downloadFile.openWrite();

  await response.stream.map((s) {
    received += s.length;
    print("${(received / length) * 100} %");
    return s;
  }).pipe(sink);

如果要写入文件,另一种方法是观察文件长度

  var length = response.contentLength;
  var sink = downloadFile.openWrite();

  Future.doWhile(() async {
    var received = await downloadFile.length();

    print("${(received / length) * 100} %");
    return received != length;
  });

  await response.stream.pipe(sink);