gpt4 book ai didi

flutter - StreamBuilder 监听流和常规监听方法的区别

转载 作者:行者123 更新时间:2023-12-03 03:00:36 28 4
gpt4 key购买 nike

我正在使用 http库以下载图像。

final client = http.Client();
final _response = await client.send(http.Request('GET', Uri.parse("my_url")));

听法一:(听法)
int downloaded = 0;
_response.stream.listen((value) {
// this gets called 82 times and I receive actual image size
downloaded += value.length;
});

聆听方式2:(StreamBuilder小部件)
int downloaded = 0;
StreamBuilder<List<int>>(
stream: _response.stream,
builder: (_, snapshot) {
// this gets called 11 times and I receive around 1/10 actual image size
if (snapshot.hasData) downloaded += snapshot.data.length;
return Container();
},
);

问题是为什么 StreamBuilderbuild()当新数据到达时,方法不会经常被调用,它只是违背了用作小部件的目的。

最佳答案

StreamBuilder基本上更好地优化为不在每个新快照上重建。如 StreamBuilder documentation状态:

Widget rebuilding is scheduled by each interaction, using State.setState, but is otherwise decoupled from the timing of the stream. The builder is called at the discretion of the Flutter pipeline, and will thus receive a timing-dependent sub-sequence of the snapshots that represent the interaction with the stream.

As an example, when interacting with a stream producing the integers 0 through 9, the builder may be called with any ordered sub-sequence of the following snapshots that includes the last one (the one with ConnectionState.done):

  • new AsyncSnapshot<int>.withData(ConnectionState.waiting, null)
  • new AsyncSnapshot<int>.withData(ConnectionState.active, 0)
  • new AsyncSnapshot<int>.withData(ConnectionState.active, 1)
  • ...
  • new AsyncSnapshot<int>.withData(ConnectionState.active, 9)
  • new AsyncSnapshot<int>.withData(ConnectionState.done, 9)

The actual sequence of invocations of the builder depends on the relative timing of events produced by the stream and the build rate of the Flutter pipeline.

关于flutter - StreamBuilder 监听流和常规监听方法的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61020493/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com