成为Flutter动画大师(三)

1,499 阅读1分钟

目录传送门:《Flutter快速上手指南》先导篇

Flutter 提供了 AnimatedWidget,用于简化动画。

继承 AnimatedWidget 实现的 Widget,不需要再手动在 addListener() 添加的回调中调用 setState()

如何使用 AnimatedWidget?

1.继承 AnimatedWidget

class AnimatedImage extends AnimatedWidget {
  AnimatedImage({Key key, Animation<double> animation})
      : super(key: key, listenable: animation);

  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return Center(
      child: SizedBox(
        // 获取 Animation 中的值
        width: animation.value,
        height: animation.value,
        child: Container(
          color: Colors.lightBlue,
       ),
    );
  }
}

关键点在于,实现 AnimatedWidget,然后在 build() 函数中创建视图。

通过 animation.value 直接获得结果,设置到视图属性上。

2.使用实现好的 AnimatedWidget

class ScaleAnimationRoute extends StatefulWidget {
  @override
  _ScaleAnimationRouteState createState() => _ScaleAnimationRouteState();
}

class _ScaleAnimationRouteState extends State<ScaleAnimationRoute>
    with SingleTickerProviderStateMixin {

  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    // 创建 AnimationController
    controller = AnimationController(
        duration: const Duration(seconds: 3), vsync: this);
    // 创建 Animation
    animation = Tween(begin: 0.0, end: 300.0).animate(controller);
    // 不需要再在 `addListener()` 添加的回调中调用 `setState()`
    // 启动动画
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    // 把刚刚创建的 animation 传入
    return AnimatedImage(animation: animation,);
  }

  dispose() {
    controller.dispose();
    super.dispose();
  }
}

你看,不需要再写 addListenersetState 这些代码!

实际上也没省多少事,哈哈哈..

目录传送门:《Flutter快速上手指南》先导篇

如何找到我?

传送门:CoorChice 的主页

传送门:CoorChice 的 Github