Home > Mobile >  Container does not change colour on tap/click
Container does not change colour on tap/click

Time:12-20

Container does not change colour on tap/click

The following widget should change the colors from red to blue when I tap/click. But it does not do anything. This widget is embedded in a parent stateful widget. What could be the issue?

Widget _myCard(BuildContext context, bool animationYESNO,
      String stringToDisplay, int index, Animation<double> animation) {
    
    Color highlightColour = Colors.redAccent;

    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: GestureDetector(
          onTap: () {
            setState(() {
              highlightColour = Colors.blueAccent;
            }); 
                           
            }
          },
          child: Container(
             color: highlightColour,
          
          )),
    );
  }

CodePudding user response:

It is changing, but immediately going back to Colors.redAccent because

Color highlightColour = Colors.redAccent; declared inside build method. Remove highlightColour from _myCard and put it above build method.

Like

  Color highlightColour = Colors.redAccent;
  @override
  Widget build(BuildContext context) {

More about StatefulWidget

CodePudding user response:

The problem is that the highlightColor variable is a local variable declared in this method, and not a field on the stateful Widget. So what is happening is that you set the local variable to Blue when the gesture detector is pressed, setState() triggers the widget to re-build, and _myCard is executed again, where highlightColor is declared and set to red. So the widget is never built with the blue color.

To fix, just move the line

Color highlightColour = Colors.redAccent;

To be a field on the state class instead of a local variable and it should work.

So, something like ...

class _YourWidgetState extends State<YourWidget> {
   Color highlightColour = Colors.redAccent;

   @override
   Widget build(BuildContext context) {

As a separate note, you don't actually need to pass in the build context to a method in the stateful widget, you can just get context anywhere in the state class.

  • Related