Flutter StreamBuilder 如何在 ConnectionState.done 时 运行 setState()?

Flutter StreamBuilder how i can run setState() when ConnectionState.done?

我正在使用 StreamBuilder 来显示加载进度条。有可能到达 ConnectionState.done - 运行 setState() 更新我在 StreamBuilder 之外的小部件?

如果我尝试从小部件调用 setState(),我会收到错误消息

setState() or markNeedsBuild() called during build

 case ConnectionState.done:
          children = <Widget>[
                    Icon(
                        Icons.info,
                        color: Colors.blue,
                         size: 60,
                         ),
                          Padding(
                            padding: const EdgeInsets.only(top: 16),
                            child: Text('$${snapshot.data} (closed)'),
                          )
                        ];
                        
                        //I'm trying to trigger an update
                        setState((){
                          isOffsetLoading = true;
                        });
                        
                        break;

来自文档: Streambuilder:https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html

Widget that builds itself based on the latest snapshot of interaction with a Stream.

设置状态:https://api.flutter.dev/flutter/widgets/State/setState.html

Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.

该错误意味着您在构建小部件时调用了 setState,这将导致小部件重复重建。

您可以更新 isOffsetLoading 并在单独的函数中调用 setState,然后在问题的代码中调用该函数。