flutter - 尝试为 ElevatedButton 设置动画时出现此错误
问题描述
我目前正在尝试为提升的按钮设置动画,只是想为提升的属性设置动画。所以我在 VS 代码中搭建了一个新的颤振启动器应用程序,并在动画和动画控制器的相关代码中添加了,但是我不断收到这个错误:类型'double'不是类型'MaterialStateProperty<double?>的子类型? ' 我不明白为什么,这是我的代码
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, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
AnimationController animationController;
Animation animation;
@override void initState() {
super.initState();
animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 5),
);
animation = Tween(begin: 50.0, end: 150.0).animate(
CurvedAnimation(
parent: animationController,
curve: Interval(0.0, 1.0, curve: Curves.easeInOut),
),
);
}
@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.forward();
},
child: Text("Button Text"),
style: ButtonStyle(
elevation: animation.value,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
解决方案
根据ButtonStyle
文档:
许多 ButtonStyle 属性是
MaterialStateProperty
对象,它们根据按钮的状态解析为不同的值。例如,颜色属性是使用 MaterialStateProperty 定义的,并且可以根据按钮是否被按下、悬停、聚焦、禁用等解析为不同的颜色。
因此,您需要做的是将animation value
作为 MaterialStateProperty 传递。
在您的情况下,它看起来像这样:
style: ButtonStyle(
elevation: MaterialStateProperty.all(animation.value),
),
查看MaterialStateProperty
Class 文档以获取更多信息。
推荐阅读
- entity-framework - 自引用表中除主键以外的导航属性
- r - R - 由于数据集,构建包非常慢
- java - Junit 5 @SpringBootTest 可执行jar
- javascript - canvas drawImage() - 将图像切成两半并取左侧部分
- multithreading - 在mac中一段时间后wxapp变得无响应
- python - Python小于大于括号
- html - 制作一个好的图像轮播
- php - ACF DateTime/Date Picker : 获取大于当前日期的帖子
- python - 如何多次迭代文件?
- python - 当我在笔记本上运行此 Python 代码时,它返回空表。我收到此错误如何克服此错误?