当前位置: 首页 > article >正文

Flutter_学习记录_动画的简单了解

AnimationController简单实现如下的效果图:
在这里插入图片描述

1. 只用AnimationController实现简单动画

1.1 完整代码案例

import 'package:flutter/material.dart';

class AnimationDemo extends StatefulWidget {
  const AnimationDemo({super.key});

  
  State<AnimationDemo> createState() => _AnimationDemoState();
}

class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateMixin {

  late AnimationController animationDemoController;
  
  void initState() {
    super.initState();

    animationDemoController = AnimationController(
      vsync: this,
      // 初始值,要在 lowerBound 和 upperBound 之间
      value: 32.0,
      // 最小值
      lowerBound: 32.0,
      // 最大值
      upperBound: 100.0,
      // 设置动画的时间
      duration: Duration(milliseconds: 3000)
    );

    animationDemoController.addListener((){
      // 更新页面
      setState(() {
        
      });
    });

    // 添加status的监听
    animationDemoController.addStatusListener((AnimationStatus status){
      print(status);
    });
  }

  
  void dispose() {
    super.dispose();
    // 销毁 animationDemoController
    animationDemoController.dispose();
  }


  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("AnimationDemo"),
      ),
      body: Center(
        child: IconButton(
          icon: Icon(Icons.favorite),
          iconSize: animationDemoController.value,
          onPressed: (){
            switch (animationDemoController.status) {
              case AnimationStatus.completed:
                // 反转动画
                animationDemoController.reverse();
                break;
              default:
                // 开始动画
                animationDemoController.forward();
            }
          },
        ),
      ),
    );
  }
}

1.2 代码说明

(1) AnimationController

  • animationDemoController 是动画的核心控制器。
  • duration 定义了动画的持续时间(例如 2 秒)。
  • vsync 参数确保动画与屏幕刷新同步,避免资源浪费。
  • value 设置初始值。
  • lowerBound 设置最小值。
  • upperBound 设置 最大值。

(2) addListener 添加监听,可以监听到 animationDemoController.value的值的变化。

  • 如果需要需要用到 animationDemoController.value的值更新UI,则需要调用 setState的方法。
animationDemoController.addListener((){
      // 更新页面
      setState(() {
        
      });
    });

(3)addStatusListener 添加动画状态的监听,只有添加了这个监听,才能在后面获取到动画状态的变化。

            switch (animationDemoController.status) {
              case AnimationStatus.completed:
                // 反转动画
                animationDemoController.reverse();
                break;
              default:
                // 开始动画
                animationDemoController.forward();
            }

(4) 开始动画

animationDemoController.forward()

(5)反转动画

animationDemoController.reverse();

2. 用AnimationControllerAnimation实现简单动画

2.1 完整代码示例

import 'package:flutter/material.dart';

class AnimationDemo extends StatefulWidget {
  const AnimationDemo({super.key});

  
  State<AnimationDemo> createState() => _AnimationDemoState();
}

class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateMixin {

  late AnimationController animationDemoController;
  late Animation animation;
  late Animation animationColor;
  // 设置动画取消
  late CurvedAnimation curve;

  
  void initState() {
    super.initState();

    animationDemoController = AnimationController(
      vsync: this,
      // 设置动画的时间
      duration: Duration(milliseconds: 3000)
    );

    animation = Tween(begin: 32.0, end: 100.0).animate(animationDemoController);
    animationColor = ColorTween(begin: Colors.red, end: Colors.green).animate(animationDemoController);

    animationDemoController.addListener((){
      // 更新页面
      setState(() {
        
      });
    });

    // 添加status的监听
    animationDemoController.addStatusListener((AnimationStatus status){
      print(status);
    });
  }

  
  void dispose() {
    super.dispose();
    // 销毁 animationDemoController
    animationDemoController.dispose();
  }


  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("AnimationDemo"),
      ),
      body: Center(
        child: IconButton(
          icon: Icon(Icons.favorite),
          iconSize: animation.value,
          color: animationColor.value,
          onPressed: (){
            switch (animationDemoController.status) {
              case AnimationStatus.completed:
                // 反转动画
                animationDemoController.reverse();
                break;
              default:
                // 开始动画
                animationDemoController.forward();
            }
          },
        ),
      ),
    );
  }
}

2.2 代码说明

(1) Tween

  • Tween(begin: xx, end:xx) 定义了动画的范围:
  • begin 是起始值。
  • end 是结束值。

(2) animationDemoController.value animation.value 来替代

3. 用AnimationControllerAnimationCurvedAnimation实现简单动画

CurvedAnimation 可以添加缓动效果(如 Curves.easeInOut),完整代码示例:

import 'package:flutter/material.dart';

class AnimationDemo extends StatefulWidget {
  const AnimationDemo({super.key});

  
  State<AnimationDemo> createState() => _AnimationDemoState();
}

class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateMixin {

  late AnimationController animationDemoController;
  late Animation animation;
  late Animation animationColor;
  // 设置动画曲线
  late CurvedAnimation curve;

  
  void initState() {
    super.initState();

    animationDemoController = AnimationController(
      vsync: this,
      // 设置动画的时间
      duration: Duration(milliseconds: 3000)
    );

    curve = CurvedAnimation(parent: animationDemoController, curve: Curves.bounceOut);
    animation = Tween(begin: 32.0, end: 100.0).animate(curve);
    animationColor = ColorTween(begin: Colors.green, end: Colors.red).animate(curve);

    animationDemoController.addListener((){
      // 更新页面
      setState(() {
        
      });
    });

    // 添加status的监听
    animationDemoController.addStatusListener((AnimationStatus status){
      print(status);
    });
  }

  
  void dispose() {
    super.dispose();
    // 销毁 animationDemoController
    animationDemoController.dispose();
  }


  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("AnimationDemo"),
      ),
      body: Center(
        child: IconButton(
          icon: Icon(Icons.favorite),
          iconSize: animation.value,
          color: animationColor.value,
          onPressed: (){
            switch (animationDemoController.status) {
              case AnimationStatus.completed:
                // 反转动画
                animationDemoController.reverse();
                break;
              default:
                // 开始动画
                animationDemoController.forward();
            }
          },
        ),
      ),
    );
  }
}

4 用AnimationControllerAnimatedWidget实现简单动画

完整代码实例:

import 'package:flutter/material.dart';

class AnimationDemo extends StatefulWidget {
  const AnimationDemo({super.key});

  
  State<AnimationDemo> createState() => _AnimationDemoState();
}

class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateMixin {

  late AnimationController animationDemoController;
  late Animation animation;
  late Animation animationColor;
  // 设置动画曲线
  late CurvedAnimation curve;

  
  void initState() {
    super.initState();

    animationDemoController = AnimationController(
      vsync: this,
      // 设置动画的时间
      duration: Duration(milliseconds: 3000)
    );

    curve = CurvedAnimation(parent: animationDemoController, curve: Curves.bounceOut);
    animation = Tween(begin: 32.0, end: 100.0).animate(curve);
    animationColor = ColorTween(begin: Colors.green, end: Colors.red).animate(curve);

    // 添加status的监听
    animationDemoController.addStatusListener((AnimationStatus status){
      print(status);
    });
  }

  
  void dispose() {
    super.dispose();
    // 销毁 animationDemoController
    animationDemoController.dispose();
  }


  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("AnimationDemo"),
      ),
      body: Center(
      	//  AnimationHeart 是基于 AnimatedWidget 创建的
        child: AnimationHeart(
          animations: [animation, animationColor], 
          controller: animationDemoController
        ),
      ),
    );
  }
}

// 基于 AnimatedWidget 创建 AnimationHeart的控件
class AnimationHeart extends AnimatedWidget {

  final List animations;
  final AnimationController controller;

  const AnimationHeart({
    super.key, 
    required this.animations, 
    required this.controller
  }) : super(listenable: controller);

  
  Widget build(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.favorite),
      iconSize: animations[0].value,
      color: animations[1].value,
      onPressed: (){
        switch (controller.status) {
          case AnimationStatus.completed:
            // 反转动画
            controller.reverse();
            break;
          default:
            // 开始动画
            controller.forward();
        }
      },
    );
  }
}

http://www.kler.cn/a/548311.html

相关文章:

  • 三维重建(十二)——3D先验的使用
  • 算法——结合经典示例了解回溯法
  • 数据结构篇
  • VM安装银河麒麟系统
  • 多模态本地部署和ollama部署Llama-Vision实现视觉问答
  • 【Docker】Docker Run 中指定 `bash` 和 `sh` 参数的区别:深入解析与实践指南
  • 如何调整 Nginx工作进程数以提升性能
  • vue3 ref/reactive 修改数组的方法
  • 【DuodooBMS】给PDF附件加“受控”水印的完整Python实现
  • 机器视觉--Halcon If语句
  • SQL-leetcode—1661. 每台机器的进程平均运行时间
  • 使用C#元组实现列表分组汇总拼接字段
  • AWS上基于Llama 3模型检测Amazon Redshift里文本数据的语法和语义错误的设计方案
  • 一、敏捷开发概述:全面理解敏捷开发的核心理念
  • 【动态规划篇】:当回文串遇上动态规划--如何用二维DP“折叠”字符串?
  • PHP 字符串处理操作技巧介绍
  • QT c++ QMetaObject::invokeMethod函数 线程给界面发送数据
  • Android Studio - 解决gradle文件下载失败
  • Django运维系统定时任务方案设计与实现
  • Go语言精进之路读书笔记(第二部分-项目结构、代码风格与标识符命名)