我正在尝试切换凸起按钮的颜色。最初,该按钮应为蓝色,并且在按下时变为灰色。现在,我有一个名为pressAttention的 bool(boolean) 值,并将其设置为false。我正在使用它最初将其设置为false。当按下按钮时,它会切换pressAttention bool(boolean) 值,但似乎该小部件再也不会更新了。

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

}

最佳答案

该按钮将需要在buildStateStatefulWidget中创建,并且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),
);

08-16 12:54