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来实现动画效果,代码要简洁的多,是更为推荐的实现方式。

相关推荐
早起的年轻人4 小时前
Flutter String 按 ,。分割
flutter
helloxmg14 小时前
鸿蒙harmonyos next flutter通信之MethodChannel获取设备信息
flutter
helloxmg15 小时前
鸿蒙harmonyos next flutter混合开发之开发package
flutter·华为·harmonyos
lqj_本人2 天前
flutter_鸿蒙next_Dart基础②List
flutter
lqj_本人2 天前
flutter_鸿蒙next_Dart基础①字符串
flutter
The_tuber_sadness2 天前
【Flutter】- 基础语法
flutter
helloxmg2 天前
鸿蒙harmonyos next flutter通信之BasicMessageChannel获取app版本号
flutter
linpengteng2 天前
使用 Flutter 开发数字钱包应用(Dompet App)
前端·flutter·firebase