如何从 (dart) Stream 更新和重建特定的 class 实例?

How to update and rebuild specific class instance from (dart) Stream?

使用 Flutter 设计一个 UI 来控制网络上的节点。当然,Flutter 应用程序中的小部件状态必须与其对应的网络节点的状态相匹配。所有网络更新都通过蓝牙进行。它们在飞镖广播 Stream 中被解密、解析和发射。 Flutter 小部件应该订阅流并反映更新(通过在一些新状态下重建,即颜色)。

我似乎找不到从流中更新单个小部件的好的解决方案。小部件的 class 实例是用 this.addressthis.name 等构建的,它们对应于每个节点的网络地址、名称等。理想情况下,每个实例化的小部件都将监听流,并重建 IFF 它所持有的 address 与监听时流值中的 address 字段相匹配。

我一直在使用 provider/consumer 因为蓝牙包依赖于它,它似乎是一个有用的工具,并且认为它会成为解决方案的一部分,但似乎无法使其工作所以远的。正在寻找有关如何构建此架构的所有指导。

使用StreamBuilder!

Widget that builds itself based on the latest snapshot of interaction with a Stream. Widget rebuilding is scheduled by each interaction, using State.setState, but is otherwise decoupled from the timing of the stream.

Youtube

上观看此视频
StreamBuilder(
          stream:  , // some stream...
          builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
            List<Widget> children;
            if (snapshot.hasError) {
              // Handle error
            } else {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  // Not currently connected to any asynchronous computation.

                  break;
                case ConnectionState.waiting:
                  // Connected to an asynchronous computation and awaiting interaction.

                  break;
                case ConnectionState.active:
                  // Connected to an active asynchronous computation.

                  break;
                case ConnectionState.done:
                  // Connected to a terminated asynchronous computation.

                  break;
              }
            }

            // Default action
        ),