Flutter中动画的实现

动画三要素

控制动画的三要素:Animation、Tween、和AnmaitionController
Animation: 产生的值的序列,有CurveAnimation等子类,, 可以将值赋值给Widget的宽高或其他属性,进而控制widget发生变化

Tween:可以定义值的变化范围, 继承自Animatable<T>,每个类都有begin和end两个属性,同时有CurveTween等子类,可以定义值在begin和end间的变化方式。

AnimationController: 动画的控制器,可以设置动画的时长,控制动画开始或者结束等

有两种方式生成Animation:

(1)_controller.drive(_curveTween)

(2)_curveTween.animate(_controller)

Widget动画相关属性

(1)Container的width、height, 控制Widget大小

(2)SlideTransition 的position, 通过Tween<Offset>控制Widget的位移

(3) Align的heightFactor, 控制Widget的展开或收起

(4) AnimatedOpacity的opacity属性,控制Widget的渐隐渐显

两种动画实现方式

Flutter中动画主要有两种实现方式,即通过addListener监听Animation的值的变化, 或者用AnimationBuilder来构建参与动画的Widget。

下面看一个通过addListener实现动画的例子

Dart 复制代码
//动画控制器
final AnimationController controller = new AnimationController(
    duration: const Duration(milliseconds: 500), vsync: this);
//创建一个值的序列,其变化方式为Curve中的淡出效果
final Animation curve =
    new CurvedAnimation(parent: controller, curve: Curves.easeOut);
//通过tween指定值的变化范围为0~255
Animation<int> animation = new IntTween(begin: 0, end: 255).animate(curve);
//监听动画状态的变化: 动画是否结束
..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          controller.reverse();
        } else if (status == AnimationStatus.dismissed) {
          controller.forward();
        }
      })
//监听Animation的值的变化,更新UI
..addListener(() {
        setState(() {
          // 将animation.value赋值给指定的Widget的属性
          _opacity = animation.value.toDouble() / 255;
        });      
    });

//动画开始    
controller.forward();

再看下如何通过AnimationBuilder构建动画:

Dart 复制代码
Widget build(BuildContext context) => Center(
        child: AnimatedBuilder(
            animation: animation,
            builder: (context, child) => Container(
                  height: animation.value,
                  width: animation.value,
                  child: child,
                ),
            child: child),
      );
}

不难看出,使用AnimationBuilder来实现动画效果,代码要简洁的多,是更为推荐的实现方式。

相关推荐
芙莉莲教你写代码5 小时前
Flutter 框架跨平台鸿蒙开发 - 科学实验指南应用
flutter·华为·harmonyos
不爱吃糖的程序媛5 小时前
Flutter鸿蒙PC应用开发实践:从零到运行
flutter·华为·harmonyos
芙莉莲教你写代码6 小时前
Flutter 框架跨平台鸿蒙开发 - 赛车游戏
flutter·游戏
芙莉莲教你写代码6 小时前
Flutter 框架跨平台鸿蒙开发 - 单位换算大师应用
flutter·华为·harmonyos
weixin_443478516 小时前
Flutter第三方常用组件包学习之状态管理
javascript·学习·flutter
九狼JIULANG6 小时前
【无标题】
android·flutter·开源·github
不爱吃糖的程序媛7 小时前
Flutter应用运行到鸿蒙PC指南
flutter·华为·harmonyos
不爱吃糖的程序媛7 小时前
Flutter OH Engine 构建指导(macOS 版本)
flutter·华为·harmonyos
芙莉莲教你写代码7 小时前
Flutter 框架跨平台鸿蒙开发 - 历史知识问答应用
flutter·华为·harmonyos
2501_9206276120 小时前
Flutter 框架跨平台鸿蒙开发 - 派对策划助手应用
flutter·华为·harmonyos