最简单的解决方案是为按钮分配某种状态,使 Container 成为 AnimatedContainer 并为装饰参数添加条件。类似于我为这个问题创建的课程。在其中,我已将您的停靠点和颜色列表设为常量,这也使您的渐变也保持不变。然后你传递一个“文本”参数,然后你可以选择有一个 onPressed 回调,它会告诉你它的状态是什么。我把它变成了一个类,以避免让 setState 被整个父小部件调用,并且给出了常量来举例说明良好的做法。尽量避免将这些东西放在构建方法中。
const _stops = [0.1, 0.5, 0.7, 0.9];
const _redColors = [
Color(0xFFD32F2F), // different color
Color(0xFFE53935),
Color(0xFFF44336),
Color(0xFFE57373),
];
const _blueColors = [
Color(0xFF1976D2),
Color(0xFF1E88E5),
Color(0xFF2196F3),
Color(0xFF64B5F6),
];
const _red = const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomLeft,
end: Alignment.topRight,
stops: _stops,
colors: _redColors,
)
);
const _blue = const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomLeft,
end: Alignment.topRight,
stops: _stops,
colors: _blueColors,
)
);
class RedBlueButton extends StatefulWidget {
final Function(bool) onPressed;
final String text;
final String submittedText;
const RedBlueButton({Key key, this.onPressed, this.text, this.submittedText}) : super(key: key);
@override
_RedBlueButtonState createState() => _RedBlueButtonState();
}
class _RedBlueButtonState extends State<RedBlueButton> {
bool pressed = false;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: (){
setState(() {
pressed = !pressed;
if(widget.onPressed != null)
widget.onPressed(pressed);
});
},
child: AnimatedContainer(
duration: kThemeChangeDuration,
decoration: pressed ? _red : _blue,
alignment: Alignment.center,
padding: EdgeInsets.symmetric(
horizontal: 10,
vertical: 5
),
child: Text(
pressed ? widget.text ?? 'submit' : widget.submittedText ?? 'sent',
style: TextStyle(
color: Colors.white
),
),
),
);
}
}