尝试为ElevatedButton添加elevation动画时报double类型不匹配错误
错误原因
ElevatedButton 的 ButtonStyle.elevation 属性不接收直接的 double 类型值,它要求传入 MaterialStateProperty<double?> 类型的对象,用于适配按钮不同交互状态(默认、按下、禁用、悬浮等)下的阴影高度,你直接传入动画输出的double值就触发了类型不匹配报错。
除此之外你的代码还缺失动画值更新的UI重绘触发逻辑,就算解决类型问题也看不到动画效果。
修复点说明
- 给Animation指定泛型为
Animation<double>,避免隐式类型转换问题 - 给动画实例添加监听器,每次值更新时调用
setState触发UI重绘 - 用
MaterialStateProperty.all(animation.value)把double值包装为elevation要求的类型 - 可选优化:按钮点击时先重置动画控制器再执行动画,支持重复点击触发效果
修正后完整代码
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin { late AnimationController animationController; late Animation<double> animation; @override void initState() { super.initState(); animationController = AnimationController( vsync: this, duration: const Duration(seconds: 5), ); animation = Tween(begin: 50.0, end: 150.0).animate( CurvedAnimation( parent: animationController, curve: const Interval(0.0, 1.0, curve: Curves.easeInOut), ), ); // 添加动画监听器触发UI重绘 animation.addListener(() => setState(() {})); } @override void dispose() { animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () { // 重置后再执行动画,支持重复触发 animationController.reset(); animationController.forward(); }, child: const Text("Button Text"), style: ButtonStyle( // 包装double值为要求的MaterialStateProperty类型 elevation: MaterialStateProperty.all(animation.value), ), ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () {}, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
内容的提问来源于stack exchange,提问作者ShatterStar
相关产品推荐
相关产品推荐

