I am trying to toggle the color of a raised button. Initially the button should be blue and when it is pressed it turns to grey. Right now I have a bool value called pressAttention and it is set to false. I am using this to initially set this the false. When the button is pressed it toggles the pressAttention bool, but it seems that the widget is never updated again.

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;

}

}

}

解决方案

This button will need to be created in the build of a State of a StatefulWidget, and the State must have a member variable bool pressAttention = false;. As Edman suggests, you need to make state changes in a setState callback for the Widget to redraw.

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),

);

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐