Home > database >  How to change the color of ElevatedButton when the function condition is met?
How to change the color of ElevatedButton when the function condition is met?

Time:09-28

I would like to change the background of the button to preset ones when I have the conditions in the function met. How can I do this?

buttonColorSwitch(){
      const a = 5;
      const b = a;
      if (b==5){
         // switch Colors.green
      }
      if (b != b) {
         // switch Colors.red
      }
      else ()
      {
        // swtitch defaultColor (blue)
      };
    }

 ElevatedButton(
          onPressed: () {},
          style: ElevatedButton.styleFrom(
            //primary:Colors.blueAccent(defaultColor), switch  Colors.green, or Colors.red 
          ),

CodePudding user response:

You can use a state variable or a method to return color

  int count = 0;

  Color buttonColorSwitch() {
    if (count == 0) {
      return Colors.cyanAccent;
    } else if (count.isEven) {
      return Colors.green;
    } else {
      return Colors.purple;
    }
  }
ElevatedButton(
  onPressed: () {
    setState(() {
      count  ;
    });
  },
  style: ElevatedButton.styleFrom(
    backgroundColor: buttonColorSwitch(),
  ),
  child: Text("BTN"),
),
  • Related