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

相关推荐
好的佩奇18 小时前
Dart 之集合元素
android·flutter·dart
恋猫de小郭1 天前
Flutter 3.50 & Dart 3.14 发布,快来看看有什么更新吧
android·前端·flutter
喵个咪2 天前
GoWind CMS 拆解:Flutter 设计系统内核——双态 token、四档断点与自适应壳层
前端·flutter·交互设计
恋猫de小郭2 天前
Flutter 大小核优化又被回滚,然后又开新提案?
android·前端·flutter
好的佩奇3 天前
蓝牙之广播与扫描
android·flutter·蓝牙
wuxianda10303 天前
2026 苹果审核 4.3 (a) 被拒全解析|Guideline 4.3a spam 马甲包拒审原因 + 避坑方案
flutter·uni-app·苹果上架
恋猫de小郭3 天前
Flutter THLC 的 WebView 滚动终于从 70 FPS 提升到 120 FPS
android·前端·flutter
好的佩奇4 天前
Dart 之扩展类型
android·flutter·dart
恋猫de小郭4 天前
Flutter 下 AOT 一个你怎么都想不出来的 Bug ,JIT 正常的计算,在 AOT 居然算错了
android·前端·flutter