Flutter-单击时如何切换RaisedButton的颜色? [英] Flutter - How do I toggle the color of a RaisedButton upon click?

查看:757
本文介绍了Flutter-单击时如何切换RaisedButton的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

推荐答案

此按钮将需要在StatefulWidgetStatebuild中创建,并且State必须具有成员变量.正如Edman所建议的那样,您需要在setState回调中进行状态更改以使Widget重绘.

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

这篇关于Flutter-单击时如何切换RaisedButton的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆