masfiq reza
masfiq reza

Reputation: 97

Can I change the background color of elevated button permanently in flutter?

I have made a list from a string and then made button from that list. Now, I want that when the button is pressed it will change it's color. Currently I have done the following but it only change the button color for a moment. Can it be permanently changed?

List<Widget> _buildButtonsWithNames() {
    for (int i = 0; i < wordlist.length; i++) {
      buttonsList.add(
        new ElevatedButton(
          onPressed: () => {
           
          },
          child: Text(wordlist[i]),
          style: ButtonStyle(
              overlayColor: getColor(Colors.white, Colors.teal),
              backgroundColor: getColor(Colors.blue, Colors.red)),
        ),
      );
    }
    return buttonsList;
  }

  MaterialStateProperty<Color> getColor(Color color, Color colorPressed) {
    final getColor = (Set<MaterialState> states) {
      if (states.contains(MaterialState.pressed)) {
        return colorPressed;
      } else {
        return color;
      }
    };
    return MaterialStateProperty.resolveWith(getColor);
  }

Upvotes: 0

Views: 2487

Answers (2)

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14775

Try below code hope its helpful to you, refer official documentation here for ElevatedButton()

Declare one boolean varible,you used Stateful widget

bool isPressed = true;

your button widget:

  SizedBox(
      width: 150,
      height: 50,
      child: ElevatedButton(
        onPressed: () {
          setState(
            () {
              isPressed = !isPressed;
            },
          );
        },
        child: Text( 'OK'),
        style: ElevatedButton.styleFrom(
          primary: isPressed ? Colors.red : Colors.green,
        ),
      ),
    ),

Your result screen before button Pressed -> enter image description here

Your result screen after button Pressed -> enter image description here

Upvotes: 1

KRISHNU R S
KRISHNU R S

Reputation: 11

Use styleFrom. It will work in your case

ElevatedButton(
      onPressed: () => {
       
      },
      style: ElevatedButton.styleFrom(

                                   //Add your conditions for button color here

                                  ),

Upvotes: 1

Related Questions