Home > Net >  How to change background color of button in flutter when selected?
How to change background color of button in flutter when selected?

Time:09-17

the image of an issue is as following

Image

CodePudding user response:

enter image description hereSizedBox( width: MediaQuery.of(context).size.width * 0.46, child: ElevatedButton( style: ButtonStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10))), backgroundColor: MaterialStateProperty.resolveWith( (Set states) { if (states.contains(MaterialState.pressed)) { return Colors.red; } else { return Colors.white; } }, ), //Background Color elevation: MaterialStateProperty.all(5), //Defines Elevation shadowColor: MaterialStateProperty.all( Colors.grey), //Defines shadowColor ), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext Context) => const community())); }, child: const Text('COMMUNITY', style: TextStyle(color: Colors.grey))), )

CodePudding user response:

Make sure you are using a stateful widget. Make one boolean value isSelected (False as default) and whenever the button is pressed setState the isSelected to true. Now go back to the button color and use the ternary operator.

isSelected? (New Color) : (Default Color)

Here is my sample code.

Container(
        padding: EdgeInsets.symmetric(horizontal: 2, vertical: 2),
        decoration: BoxDecoration(
          border: Border.all(
            color: foodtype == 'Veg' ? Colors.green : Colors.red,
          ),
        ),
        child: Icon(
          Icons.circle,
          color:
              foodtype == 'Veg' ? Color.fromARGB(255, 31, 177, 36) : Colors.red,
        ),
      ),
  • Related