实现ElevatedButton与OutlinedButton的平滑动画切换
要实现两种按钮样式的平滑过渡,推荐使用Flutter内置的AnimatedSwitcher组件——它专门用于在子组件切换时自动添加过渡动画。以下是修改后的完整代码:
class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { var _highlighted = false; void _onPressed() { setState(() { _highlighted = !_highlighted; }); } @override Widget build(BuildContext context) { const buttonContent = Text('Button'); return Scaffold( body: Center( child: AnimatedSwitcher( // 设置动画时长,控制过渡快慢 duration: const Duration(milliseconds: 300), // 自定义过渡动画组合,实现淡入淡出+缩放的平滑效果 transitionBuilder: (child, animation) { return FadeTransition( opacity: animation, child: ScaleTransition( scale: animation, child: child, ), ); }, child: _highlighted ? ElevatedButton( // 给按钮设置唯一key,让AnimatedSwitcher识别组件变化 key: const ValueKey('elevated_btn'), onPressed: _onPressed, child: buttonContent, ) : OutlinedButton( key: const ValueKey('outlined_btn'), onPressed: _onPressed, child: buttonContent, ), ), ), ); } }
关键细节说明:
- 必须设置唯一Key:如果两个按钮没有不同的
key,AnimatedSwitcher会判定为同一组件,不会触发过渡动画。这里用ValueKey给两个按钮分别标记唯一标识。 - 自定义过渡效果:示例中组合了
FadeTransition和ScaleTransition,你也可以根据需求替换成其他过渡(比如SlideTransition实现滑动切换)。 - 统一按钮尺寸:默认情况下两种按钮尺寸基本一致,若切换时出现跳动,可给两个按钮设置相同的
style参数,固定宽高或内边距。
如果想要更贴合Material Design风格的过渡,还可以使用MaterialSwitchTransition:
transitionBuilder: (child, animation) { return MaterialSwitchTransition( animation: animation, child: child, ); }
内容的提问来源于stack exchange,提问作者Valentin Vignal
相关产品推荐
相关产品推荐

