Flutter中如何为ElevatedButton.icon()的图标添加按压旋转动画?
要实现点击按钮后图标旋转几秒的效果,你可以借助Flutter的AnimationController和AnimatedBuilder来完成,以下是具体实现方案:
步骤说明
- 用
AnimationController控制动画的时长与状态 - 通过
Tween和CurvedAnimation定义旋转角度的变化逻辑 - 用
AnimatedBuilder包裹图标,将动画值应用到旋转变换中 - 点击按钮时触发动画,动画结束后重置状态
完整代码示例
import 'package:flutter/material.dart'; class SyncButton extends StatefulWidget { const SyncButton({super.key}); @override State<SyncButton> createState() => _SyncButtonState(); } class _SyncButtonState extends State<SyncButton> with SingleTickerProviderStateMixin { late AnimationController _animationController; late Animation<double> _rotationAnimation; @override void initState() { super.initState(); // 初始化动画控制器,设置旋转时长为2秒 _animationController = AnimationController( vsync: this, duration: const Duration(seconds: 2), ); // 定义旋转动画:从0到2π(完整一圈),使用线性曲线保证匀速旋转 _rotationAnimation = Tween<double>(begin: 0, end: 2 * 3.14159) .animate(CurvedAnimation(parent: _animationController, curve: Curves.linear)); } @override void dispose() { // 释放控制器,避免内存泄漏 _animationController.dispose(); super.dispose(); } void _startRotation() async { // 启动旋转动画 await _animationController.forward(); // 动画结束后重置到初始状态,方便下次触发 _animationController.reset(); } @override Widget build(BuildContext context) { return ElevatedButton.icon( onPressed: _startRotation, icon: AnimatedBuilder( animation: _rotationAnimation, builder: (context, child) { return Transform.rotate( angle: _rotationAnimation.value, child: child, ); }, child: const Icon(Icons.sync), ), label: const Padding( padding: EdgeInsets.symmetric(horizontal: 8.0), child: Text("Sincronizza"), ), ); } }
代码解释
SingleTickerProviderStateMixin为动画提供帧回调支持,保证动画流畅运行_animationController负责控制动画的启动、暂停与重置_rotationAnimation定义了旋转角度的变化范围,从0到完整一圈AnimatedBuilder会在动画值更新时自动重建子组件,将旋转变换应用到图标上_startRotation方法先启动动画,等待动画完成后重置控制器,确保下次点击能再次触发旋转
内容的提问来源于stack exchange,提问作者enrico cristaudo
相关产品推荐
相关产品推荐

