飞镖-单击飞镖后如何更改我的button的颜色?

时间:2020-03-02 21:05:04

标签: flutter dart

因此,我一直在努力为Flutter应用程序将按钮的颜色从绿色更改为红色。大多数在线资源使我感到困惑。这是我的以下代码。

new RaisedButton(key:null, onPressed:buttonPressed,
                    color: Colors.green,
                    child:
                      new Text(
                      "10:00 A.M. - 11:00 A.M.",
                        style: new TextStyle(fontSize:15.0,
                        color: const Color(0xFF000000),
                        fontWeight: FontWeight.w200,
                        fontFamily: "Roboto"),
                      )
                    ),void buttonPressed(){
    }

我想单击它,它变成绿色,甚至更好。单击它,它变成灰色。然后单击另一个状态为“确认”的按钮,这将使所有已单击的灰色按钮变为红色。无论如何,我只是想了解如何在单击按钮后更改按钮的颜色。

2 个答案:

答案 0 :(得分:0)

基本上,您需要做的是

  • 使RaisedButton为类级别的变量着色,而不是像现在这样为常量着色。
  • 通过initState方法将该变量初始化为某个颜色值。
  • 在RaisedButton的onPressed处理程序中,执行以下操作:
    • 将该变量更改为您喜欢的某个颜色值。
    • 触发重新绘制(以便绘制新颜色),即调用setState方法。

最后但并非最不重要的一点是,您需要将所有代码置于有状态窗口小部件的上方。

希望很清楚,让我们知道您是否还需要一些代码示例。

答案 1 :(得分:0)

bool turnToRed = false;
bool colorIsGreen = true;

RaisedButton(key:null, onPressed: (){
   setState((){
     colorIsGreen = !colorIsGreen;
   });
},
                color: colorIsGreen ? Colors.green :turnToRed ? Colors.red : Colors.grey,
                child:
                  new Text(
                  "10:00 A.M. - 11:00 A.M.",
                    style: new TextStyle(fontSize:15.0,
                    color: const Color(0xFF000000),
                    fontWeight: FontWeight.w200,
                    fontFamily: "Roboto"),
                  )
                ),
RaisedButton(key:null, onPressed: (){
   setState((){
     turnToRed = !turnToRed;
   });
},
                color: Colors.red
                child:
                  new Text(
                  "Confirm",
                    style: new TextStyle(fontSize:15.0,
                    color: const Color(0xFF000000), 
                    fontWeight: FontWeight.w200,
                    fontFamily: "Roboto"),
                  )
                ),