Home > Mobile >  Button Colour Won't Change When Pressed
Button Colour Won't Change When Pressed

Time:06-21

I have created a button with a condition when pressed, but I am confused about how to make the button change color when pressed.

Expanded(
                    child: ProductivityButton(
                        color: const Color.fromARGB(255, 0, 162, 255),
                        text: 'Work',
                        onPressed: () => timer.startWork())),
                Padding(
                  padding: EdgeInsets.all(defaultPadding),
                ),

the productivty button is

class ProductivityButton extends StatelessWidget {
  final Color color;
  final String text;
  final double size;
  final VoidCallback onPressed;

  const ProductivityButton({
    Key? key,
    required this.color,
    required this.text,
    this.size = 0,
    required this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      onPressed: onPressed,
      child: Text(text, style: const TextStyle(color: Colors.white)),
      color: color,
      minWidth: size,
    );
  }
}

CodePudding user response:

Use setState to change the color of your button like below.

Color buttonColor = Color.fromARGB(255, 0, 162, 255);

Expanded(
    child: ProductivityButton(
        color: buttonColor,
         text: 'Work',
         onPressed: () {
            timer.startWork();
             buttonColor = Colors.red;
             setState( () {});
         }),
         Padding(
             padding: EdgeInsets.all(defaultPadding),
          ),

CodePudding user response:

Update your ProductivityButton widget with Elevated button and set overlay color property.

ElevatedButton(
  onPressed: () {},
  style: ButtonStyle(
    overlayColor: MaterialStateProperty.resolveWith<Color?>(
      (Set<MaterialState> states) {
        if (states.contains(MaterialState.pressed))
          return Colors.redAccent; //<-- SEE HERE
        return null; // Defer to the widget's default.
      },
    ),
  ),
  child: const Text(
    'Elevated Button 1',
    style: TextStyle(fontSize: 24),
  ),
)

CodePudding user response:

Expanded(
            child: ProductivityButton(
                color: const Color.fromARGB(255, 0, 162, 255),
                text: 'Work',
                onPressed: () {
                  timer.startWork();
                  setState(() {});
                })),
        Padding(
          padding: EdgeInsets.all(defaultPadding),
        ),
  • Related