简体   繁体   English

flutter 如何在单击时更改按钮的颜色

[英]flutter how to change the color of a button on a click

I am trying to change the color of the button when I click on it.当我单击它时,我正在尝试更改按钮的颜色。 Can you help me because I really can't do it.你能帮我吗,因为我真的做不到。 Thank you.谢谢你。

 Container(

        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              new MaterialButton(
                  child: new Text("1"),
                  color: Colors.greenAccent,
                splashColor: Colors.red,
                  onPressed:  (){
                    test=0;
                    test=1;



},




 ),
              new MaterialButton(
                child: new Text("2"),
                  color: Colors.greenAccent,
                    onPressed: (){
                    test=0;
                    test=2;

},

Try like this像这样试试

Color mySplashColor=Colors.blue; //define in build function or state class

splashColors: mySplashColor,
onPressed(){
setState(){
splashColors=Colors.red;
}
}

The way to do it is by using state.方法是使用 state。 The first thing you should do is to transform your widget into a stateful widget .您应该做的第一件事是将您的小部件转换为有状态的小部件

After that you set a state variable of type Color called buttonColor to have the default value of "Colors.greenAccent".之后,您将名为 buttonColor 的 Color 类型的 state 变量设置为具有默认值“Colors.greenAccent”。 You then set your MaterialButton color property to this variable.然后将 MaterialButton 颜色属性设置为此变量。

The only thing to do now is to use () => setState(() => buttonColor = Colors.red ) as the button onPressed property.现在唯一要做的就是使用 () => setState(() => buttonColor = Colors.red ) 作为按钮的 onPressed 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM