Flutter 显式动画

发布时间 2023-12-23 16:51:22作者: angelwgh

创建 AnimationController 的同时,也赋予了一个 vsync 参数。 vsync 的存在防止后台动画消耗不必要的资源。您可以通过添加 SingleTickerProviderStateMixin 到类定义,将有状态的对象用作 vsync

因为addListener() 函数调用 setState(),所以每次 Animation 生成一个新的数字,当前帧就被标记为 dirty,使得 build() 再次被调用。在 build() 函数中,container 会改变大小,因为它的高和宽都读取 animation.value,而不是固定编码值。当 State 对象销毁时要清除控制器以防止内存溢出。

class _AnimateContentState extends State<AnimateContent>
    with SingleTickerProviderStateMixin {
  bool flag = false;
  late AnimationController _controller;
  late Animation<double> animation;

  @override
  void initState() {
    // TODO: implement dispose
    super.initState();
    _controller =
        AnimationController(duration: const Duration(seconds: 1), vsync: this);
    //animate() 方法会返回一个 Animation
    animation = Tween<double>(begin: 0, end: 300).animate(_controller)
      ..addListener(() {
        setState(() {});
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          margin: const EdgeInsets.symmetric(vertical: 10),
          width: animation.value,
          height: animation.value,
          child: const FlutterLogo(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _controller.forward();
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}