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

Flutter - How do I toggle the color of a RaisedButton upon click?(Flutter - 如何在点击时切换 RaisedButton 的颜色?)

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

问题描述

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

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

}

推荐答案

这个按钮需要在 StatefulWidget 的 Statebuild 中创建,并且State必须有一个成员变量bool pressAttention = false;.正如 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 的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Flutter - 如何在点击时切换 RaisedButton 的颜色?

基础教程推荐