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

Time:11-27

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

CodePudding user response:

Use styleFrom. It will work in your case

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

                                   //Add your conditions for button color here

                                  ),

CodePudding user response:

Try below code hope its helpful to you, refer official documentation enter image description here

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

  • Related