【问题标题】:StreamBuilder updating only on end of the stream in FlutterStreamBuilder 仅在 Flutter 中的流结束时更新
【发布时间】:2019-10-09 06:09:18
【问题描述】:

我有这个流应该处理细分为帧的繁重工作负载:

Stream<int> _test() async* {
for(int i = 0; i < 50; i++){

  ///Heavy workload simulation
  for(int x = 0; x < 100000; x++){
    double _r = Random().nextDouble();
  }
  print(i);
  yield i;
  }
}

然后我使用 StreamBuilder 显示一个简单的指标:

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text(widget.title),
  ),
  body: Center(
    child: Column(
      children: <Widget>[
        StreamBuilder<int>(
          stream: _test(),
          initialData: 0,
          builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
            return Text(
              '${snapshot.data}',

            );
          },
        ),
        RaisedButton(onPressed: () {_test();})
      ],
    ),
  ),

);

}

但是当我执行代码时,i 的所有值(从 0 到 49)都会有一点延迟打印,所以_test 流不是即时的。但是 UI 只在 49 处更新,所以当流结束时。

我做错了吗?

【问题讨论】:

    标签: user-interface dart flutter stream


    【解决方案1】:

    StreamBuilder 将使用伴随ConnectionState.donesnapshot 构建其组件,在您的情况下,这是您的_test() 函数完成执行时的最后一个值(49),因为连续分配它们不允许更早操作完成。

    一种解决方案是添加Future.delayed()。这将允许每次迭代在移动到下一个值之前完全流式传输。所以_test()应该修改为:

     Stream<int> _test() async* {
        for(int i = 0; i < 50; i++){
    
          ///Heavy workload simulation
          for(int x = 0; x < 100000; x++){
            double _r = Random().nextDouble();
          }
          print(i);
          // Delay duration is arbitrarily chosen 
          await Future.delayed(Duration(milliseconds:10), () {
          });
    
          yield i;
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 2021-09-27
      • 2020-03-26
      • 2021-02-21
      • 2020-10-15
      • 1970-01-01
      • 2021-10-09
      • 2021-10-19
      • 2019-10-26
      相关资源
      最近更新 更多