gpt4 book ai didi

flutter - 如何更改独特的RaisedButton的颜色?

转载 作者:行者123 更新时间:2023-12-03 03:39:50 27 4
gpt4 key购买 nike

我有一个字符串列表:

List _choice = ["Europe","Asia","Africa"];



对于每个值,我生成RaisedButton:
enter image description here

我还有另一个变量:

String answer = "Europe";



我的目标:
如果用户单击任何“凸起”按钮,则将“文本值”等于“答案”值的颜色更改为绿色。对于其他“文本”值不等于“答案”的值,请将颜色更改为红色。

我的代码的问题是所有RaisedButton更改为红色或绿色。
 Widget build(BuildContext context) {
List<String> _choice = <String>["Europe","Asia","Africa"];
String answer = "Europe";
int NumberChoice = _choice.length;

//RaisedButtons
for (var i = 0; i < NumberChoice; i++)
new RaisedButton(
color: _colorButton,
child: new Text(
_choice[i],
style: new TextStyle(
fontSize: 20.0, color: Colors.white),
),
onPressed: () {
setState(() {
if (_choice[i] == answer) {
print("--------------- Corect ----------------");
_colorButton = Colors.greenAccent;
scoreResult = 1;
} else {
print("--------------- False ------------------------");
_colorButton = Colors.redAccent;
scoreResult = 0;
}
});
},
),

最佳答案

我终于解决了你的案子这需要大量的努力,但最后,我们就在那里。

我所做的是,我按了并按了一下按钮,就重新构建了小部件,并更改了RaisedButton()的颜色键本身的颜色

我知道这听起来会有些复杂,但是在研究了解决方案之后,您将得到它。

在转向解决方案之前,这里是演示。默认情况下,按钮是粉红色的,一旦我按下任何按钮,结果就会显示出来,错误答案=红色,右边=绿色

Demo of the result

class RadioButtonPage extends StatefulWidget {
@override
RadioButtonPageState createState() => RadioButtonPageState();

}

class RadioButtonPageState extends State<RadioButtonPage> {

List<String> _choice = ["Europe","Asia","Africa"];
String answer = "Europe";
var score;

//this bool does the real magic since you want the result to be seen on the press of the button, so here you go, this keeps track of the pressed button whether it is pressed once or not
bool isPressedOnce = false;

List<Widget> getButtons(){
List<Widget> _listWidget = [];
for(int i=0; i< _choice.length; i++){
_listWidget.add(
RaisedButton(
//Everytime it builds up, it will work according to this situation, hence works
color: isPressedOnce ? (_choice[i] == answer ? Colors.greenAccent : Colors.red) : Colors.pink,
child: Text(_choice[i]),
onPressed: (){
//Changes the state of bool to true, since any button is pressed
setState(() {
this.isPressedOnce = true;
if(_choice[i] == this.answer) score = 1;
else score = 0;
});

//Rebuilding the widget again, and now with the current condition I have put on that color key, it will finally work as per the requirements
this.getButtons();
}
)
);
}

return _listWidget;
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Welcome'),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: this.getButtons()
)
)
);
}
}

关于flutter - 如何更改独特的RaisedButton的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57843157/

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