我有一个RaisedButton
。我想每次用户单击时,将其颜色从绿色变为红色,反之亦然。
这怎么办?
答案 0 :(得分:4)
class ChangeRaisedButtonColor extends StatefulWidget {
@override
ChangeRaisedButtonColorState createState() => ChangeRaisedButtonColorState();
}
class ChangeRaisedButtonColorState extends State<ChangeRaisedButtonColor>
with SingleTickerProviderStateMixin {
AnimationController _animationController;
Animation _colorTween;
@override
void initState() {
_animationController =
AnimationController(vsync: this, duration: Duration(milliseconds: 300));
_colorTween = ColorTween(begin: Colors.red, end: Colors.green)
.animate(_animationController);
super.initState();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _colorTween,
builder: (context, child) => RaisedButton(
child: Text("Change my color"),
color: _colorTween.value,
onPressed: () {
if (_animationController.status == AnimationStatus.completed) {
_animationController.reverse();
} else {
_animationController.forward();
}
},
),
);
}
}
答案 1 :(得分:3)
您可以将 AnimatedContainer 用作riseButton child。并在更改颜色时将其动画化!
RaisedButton(
onPressed: null,
padding: EdgeInsets.all(0),
child: AnimatedContainer(
color: pageIndex == 1 ? Color(0xFF4B4B4B) : Color(0xFFD8D8D8),
duration: Duration(milliseconds: 300),
),
)
及其只是一个容器,因此可以有类似文本的子项。