使用 StreamBuilder 制作动画

Animation with StreamBuilder

项目

你好, 我用 flutter 创建了一个简单的应用程序,它根据用户垂直拖动使用 streambuilder 更改容器的高度。

因为用户输入更新非常快,这迫使 streambuider 重建多次,创建动画效果。

代码

    final StreamController streamController = StreamController<double>();
    double height = 0.0;

    StreamBuilder(
      initialData: 0.0,
      stream: streamController.stream,
      builder: (context, snapshot) {
        return Container(
          height: snapshot.data,
        );
      },
    ),

     ....

     height += (dragUpdateDY);
     streamController.add(height);

问题

尽管代码按预期工作,但我一直认为这不是一个好的解决方案,因为它迫使 UI 在一秒钟内重建不可预测的时间量,甚至可能超过 60 次,超过显示刷新率。

有没有更好的方法?

这完全没问题,因为 build 实际上 不是 由您调用!它总是被框架调用,这就是为什么它不会被调用超过 60 Hz。
这是真的,因为 StreamBuilder 在内部调用 State.setState,它执行以下操作:

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.

如果您想要更细粒度的控制,您可以创建自己的 RenderObject and call markNeedsPaint or markNeedsLayout whenever you need it based on GestureRecognizers。