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

相关推荐
测试人社区—667919 小时前
提升测试覆盖率的有效手段剖析
人工智能·学习·flutter·ui·自动化·测试覆盖率
子春一20 小时前
Flutter 与 AI 融合开发实战:在移动端集成大模型、智能推荐与生成式 UI
人工智能·flutter·ui
克喵的水银蛇1 天前
Flutter 通用底部弹窗:ActionSheetWidget 一键实现自定义选项与交互
flutter
小a彤1 天前
Flutter 深度解析:跨平台开发的终极利器
flutter
_大学牲1 天前
Flutter 勇闯2D像素游戏之路(二):绘制加载游戏地图
flutter·游戏·游戏开发
程序员老刘1 天前
千万别再纠结Flutter状态管理,90%项目根本不需要选
flutter·客户端
renxhui1 天前
Flutter 常用组件全属性说明(持续更新中)
flutter
m0_看见流浪猫请投喂1 天前
Flutter鸿蒙化现有三方插件兼容适配鸿蒙平台
flutter·华为·harmonyos·flutterplugin·flutter鸿蒙化
雨季6661 天前
Flutter 智慧物流仓储服务平台:跨端协同打造高效流转生态
flutter
勇气要爆发1 天前
【第五阶段—高级特性和框架】第十一章:Flutter屏幕适配开发技巧—变形秘籍
flutter