gpt4 book ai didi

flutter - 在 Flutter/Dart 中动态更改按钮的背景颜色

转载 作者:行者123 更新时间:2023-12-03 04:46:33 25 4
gpt4 key购买 nike

用户单击按钮时如何动态更改按钮的颜色。以下代码生成带有随机数的按钮。需要检查

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++;
}

最佳答案

是状态。例如,下面的小部件呈现一行按钮(它接受一个参数 number,它是一个整数 - 要呈现的按钮的数量)。

当您单击一个按钮时,它会更新设置单击哪个按钮的索引状态,将颜色从红色更改为蓝色。

注意:这可能不是您想要做的 - 您可能希望在单击时突出显示所有按钮。没关系,概念是你需要使用状态跟踪点击次数。


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 框架(angular、vue、flutter、react),我都能找到 lifting state up通过 react 非常有用。

把 state 放在你需要的地方,并且只放在你需要的地方。

关于flutter - 在 Flutter/Dart 中动态更改按钮的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62173223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com