一尘不染

Flutter-单击时如何切换RaisedButton的颜色?

flutter

我正在尝试切换凸起按钮的颜色。最初,该按钮应为蓝色,并且在按下时变为灰色。现在,我有一个名为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;
  }
}

}


阅读 1297

收藏
2020-08-13

共1个答案

一尘不染

此按钮将需要在将要创建buildStateStatefulWidget,国家必须有一个成员变量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),
);
2020-08-13