【问题标题】:Why does AnimationController needs a vsync?为什么 AnimationController 需要 vsync?
【发布时间】:2020-04-05 08:52:22
【问题描述】:

使用AnimationController时,那个vsync参数的作用是什么?

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> with SingleTickerProviderStateMixin {
  AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this, // Why do we need this?
    );
  }

  // ...
}

【问题讨论】:

    标签: flutter animation


    【解决方案1】:

    AnimationControllervsync参数有一个用途:根据外部因素控制动画的进度。

    通常有三种主要用途:

    • “慢动画”之类的开发工具,可将AnimationControllers 的速度降低 50%。
    • 小部件测试。通过使用vsync,这允许测试跳过帧以针对非常特定的动画状态。这既精确又不涉及实时等待。
    • 当与 SingleTickerProviderStateMixin 关联的小部件不再可见时,它允许动画“静音”

    最后一个场景是我们的小部件需要SingleTickerProviderStateMixin 的主要原因。 知道与动画相关联的小部件很重要。我们不能只使用从应用程序的根小部件获得的TickerProvider

    通过vsync,这将避免我们的小部件不再可见的情况(例如,如果另一个路由被推到它的顶部),但动画仍在播放,因此使我们的屏幕不断刷新

    查看该行为的一种方法是使用“性能叠加”开发工具与CircularProgressIndicator 等小部件相结合,它在内部使用AnimationController

    如果我们使用Opacity 来隐藏我们的指示器(它不会暂停动画):

    Opacity(
      opacity: 0,
      child: CircularProgressIndicator(),
    )
    

    然后性能叠加显示我们的屏幕一直在刷新:

    现在,如果我们添加 TickerMode(由 VisibilityNavigator 等小部件隐式完成),我们可以暂停动画,从而停止不必要的刷新:

    Opacity(
      opacity: 0,
      child: TickerMode(
        enabled: false,
        child: CircularProgressIndicator(),
      ),
    ),
    

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2020-05-03
      • 2020-03-22
      • 2011-08-11
      相关资源
      最近更新 更多