Flutter-单击时如何切换RaisedButton的颜色?
我正在尝试切换凸起按钮的颜色。最初,该按钮应为蓝色,并且在按下时变为灰色。现在,我有一个名为pressAttention的布尔值,并将其设置为false。我正在使用它最初将其设置为false。当按下按钮时,它会切换pressAttention布尔值,但似乎该小部件再也不会更新了。
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;
  }
}
}
回答:
此按钮将需要在将要创建build的State的StatefulWidget,国家必须有一个成员变量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),
);
以上是 Flutter-单击时如何切换RaisedButton的颜色? 的全部内容, 来源链接: utcz.com/qa/434078.html








