[英]Change Background Color of button dynamically in Flutter / Dart
用户单击按钮时如何动态更改按钮的颜色。 以下代码生成带有随机数的按钮。 需要检查
for (var j = 0; j < 5; j++) {
rowOfButtons.add(SizedBox(
width: 70,
height: 70,
child: Padding(
padding: EdgeInsets.all(5.0),
child: FlatButton(
color: Colors.blue,
textColor: Colors.white,
disabledColor: Colors.grey,
disabledTextColor: Colors.black,
splashColor: Colors.blueAccent,
onPressed: () {
/*...*/
},
child: Text(
numberlist[addrow].toString(),
style: TextStyle(fontSize: 20.0),
),
))));
addrow++;
count++;
}
它是 state。 例如,下面的小部件呈现一行按钮(它接受一个参数number
,即 integer - 要呈现的按钮数量)。
当您单击一个按钮时,它会更新设置单击哪个按钮的索引的 state,将颜色从红色更改为蓝色。
注意:这可能不是您想要做的 - 您可能希望在单击时突出显示所有按钮。 没关系,概念是您需要使用 state来跟踪点击。
class RowOfButtons extends StatefulWidget {
RowOfButtons({Key key, this.number}) : super(key: key);
final int number;
@override
RowOfButtonsState createState() => RowOfButtonsState();
}
class RowOfButtonsState extends State<RowOfButtons> {
int tapped;
@override
Widget build(BuildContext context) {
List<Widget> buttons = new List();
print(widget.number);
for(var i = 0;i < widget.number; i++) {
buttons.add(
SizedBox(
width: 40,
height:40,
child: Padding(
padding: EdgeInsets.all(5.0),
child: FlatButton(
color: tapped == i ? Colors.blue : Colors.red,
textColor: Colors.white,
disabledColor: Colors.grey,
disabledTextColor: Colors.black,
splashColor: Colors.blueAccent,
child: Text("I am button '$i'"),
onPressed: () { setState(() { tapped = i; }); },
),
)
)
);
}
return Row(children: buttons);
}
}
编辑:您可以通过创建自己的 Button 小部件来做得更好,如下所示:
class MyClickedButton extends StatefulWidget {
MyClickedButton({Key key, this.onPressed}) : super(key: key);
// allow the widget that renders this widget to pass
// in a callback for when the button is pressed
final Function() onPressed;
@override
MyClickedButtonState createState() => MyClickedButtonState();
}
class MyClickedButtonState extends State<MyClickedButton> {
bool pressed;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 40,
height:40,
child: Padding(
padding: EdgeInsets.all(5.0),
child: FlatButton(
color: pressed ? Colors.blue : Colors.red,
textColor: Colors.white,
disabledColor: Colors.grey,
disabledTextColor: Colors.black,
splashColor: Colors.blueAccent,
child: Text("I am a button"),
onPressed: () {
setState(() => { pressed = !pressed });
// call the callback that was passed in from the parent widget
widget.onPressed();
},
),
)
);
}
}
无论您使用什么 UI 框架(角度、vue、flutter、react),我发现通过 react提升 state非常有用。
将 state 放在您需要的地方,并且只放在您需要的地方。
使用生成随机颜色
color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.