【问题标题】:Difference between listening of stream by StreamBuilder and regular listen methodStreamBuilder 监听流和普通监听方法的区别
【发布时间】:2020-04-03 21:14:25
【问题描述】:

我正在使用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;
});

收听方式二:(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() 方法没有在新数据到达时经常被调用,它完全违背了用作小部件的目的。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    StreamBuilder 基本上得到了更好的优化,不会在每个新快照上重新构建。正如StreamBuilder documentation 所说:

    小部件重建由每次交互安排,使用 State.setState,但在其他方面与 溪流。构建器由 Flutter 自行决定调用 流水线,因此将接收到一个与时间相关的子序列 代表与流交互的快照。

    例如,当与产生整数 0 的流交互时 通过 9,可以使用任何有序的子序列调用构建器 以下快照包括最后一张(带有 ConnectionState.done):

    • new AsyncSnapshot&lt;int&gt;.withData(ConnectionState.waiting, null)
    • new AsyncSnapshot&lt;int&gt;.withData(ConnectionState.active, 0)
    • new AsyncSnapshot&lt;int&gt;.withData(ConnectionState.active, 1)
    • ...
    • new AsyncSnapshot&lt;int&gt;.withData(ConnectionState.active, 9)
    • new AsyncSnapshot&lt;int&gt;.withData(ConnectionState.done, 9)

    构建器的实际调用顺序取决于流产生的事件的相对时间和 Flutter 管道的构建速率。

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 2017-04-10
      • 2022-08-19
      • 2014-07-25
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多