Flutter实现ElevatedButton按压时平滑放大10%的动画效果
可以通过GestureDetector配合AnimationController和ScaleTransition来实现这个需求,下面是完整的实现代码:
import 'package:flutter/material.dart'; class ScalingElevatedButton extends StatefulWidget { final String text; final VoidCallback onPressed; const ScalingElevatedButton({ super.key, required this.text, required this.onPressed, }); @override State<ScalingElevatedButton> createState() => _ScalingElevatedButtonState(); } class _ScalingElevatedButtonState extends State<ScalingElevatedButton> with SingleTickerProviderStateMixin { late AnimationController _animationController; late Animation<double> _scaleAnimation; @override void initState() { super.initState(); // 初始化动画控制器,设置200ms时长保证平滑过渡 _animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 200), ); // 定义从1.0到1.1的缩放动画(放大10%) _scaleAnimation = Tween<double>(begin: 1.0, end: 1.1).animate( CurvedAnimation(parent: _animationController, curve: Curves.easeInOut), ); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return GestureDetector( // 触摸按下时启动放大动画 onTapDown: (_) => _animationController.forward(), // 触摸抬起或取消时恢复原尺寸 onTapUp: (_) => _animationController.reverse(), onTapCancel: () => _animationController.reverse(), // 用ScaleTransition实现缩放效果 child: ScaleTransition( scale: _scaleAnimation, child: ElevatedButton( // 移除默认水波纹反馈 style: ElevatedButton.styleFrom( splashFactory: NoSplash.splashFactory, ), onPressed: widget.onPressed, child: Text(widget.text), ), ), ); } } // 使用示例 void main() { runApp(const MaterialApp( home: Scaffold( body: Center( child: ScalingElevatedButton( text: "触摸放大按钮", onPressed: () {}, ), ), ), )); }
关键说明:
- 动画控制:
AnimationController负责动画的启动与反转,你可以调整Duration参数来改变过渡快慢。 - 触摸监听:
GestureDetector覆盖了所有触摸场景,确保按钮在任何情况下都能正确恢复原尺寸。 - 移除水波纹:通过设置
splashFactory: NoSplash.splashFactory,彻底关闭按钮默认的水波纹效果。 - 缩放逻辑:
ScaleTransition配合Tween实现精准的10%放大,Curves.easeInOut让动画过渡更自然。
内容的提问来源于stack exchange,提问作者androidneil
相关产品推荐
相关产品推荐

