dragon1980
dragon1980

Reputation: 1

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;

},

Upvotes: 0

Views: 2014

Answers (2)

Kallas Lima Antunes
Kallas Lima Antunes

Reputation: 1

The way to do it is by using 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". You then set your MaterialButton color property to this variable.

The only thing to do now is to use () => setState(() => buttonColor = Colors.red ) as the button onPressed property.

Upvotes: 0

guccisekspir
guccisekspir

Reputation: 1377

Try like this

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

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

Upvotes: 2

Related Questions