我正在尝试切换凸起按钮的颜色。最初按钮应该是蓝色的,当它被按下时它会变成灰色。现在我有一个名为 pressAttention 的 bool 值,它被设置为 false。我正在使用它来最初将其设置为 false。当按下按钮时,它会切换 pressAttention bool,但似乎小部件永远不会再次更新。
new RaisedButton(
child: new Text("Attention"),
textColor: Colors.white,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
color: pressAttention?Colors.grey:Colors.blue,
onPressed: () => doSomething("Attention"),
)
void doSomething(String buttonName){
if(buttonName == "Attention"){
if(pressAttention = false){
pressAttention = true;
} else {
pressAttention = false;
}
}
}
最佳答案
这个按钮需要在StatefulWidget
的State
的build
中创建,并且State必须有一个成员变量bool pressAttention = false;
.正如 Edman 建议的那样,您需要在 setState
回调中进行状态更改,以便 Widget 重绘。
new RaisedButton(
child: new Text('Attention'),
textColor: Colors.white,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
color: pressAttention ? Colors.grey : Colors.blue,
onPressed: () => setState(() => pressAttention = !pressAttention),
);
关于android - Flutter - 如何在点击时切换 RaisedButton 的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50863681/