vishal
vishal

Reputation: 89

How to change the color of a icon on tap and when released the color should go back to default color

I have a scenario where, when a button is pressed the color of the button should change and then when I release the press the color should change back to its default color.

I'm using GestureDetector widget to do that, Can someone help me?

bool color = false;

GestureDetector(
   onTap: () {
       setState(() {
          if (age > 3) {
              color = true;
               age--;
          } 
          color = false;
       });
   },
   child: Icon(
       Icons.indeterminate_check_box,
       color: color
         ? kSelectedIconColor
         : kAppbarColor,
       size: 40.0,
   )
)

Upvotes: 0

Views: 2145

Answers (1)

Saman Salehi
Saman Salehi

Reputation: 2179

class TapIcon extends StatefulWidget {
  @override
  _TapIconState createState() => _TapIconState();
}

class _TapIconState extends State<TapIcon> {
  bool tapped = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (_) {
        setState(() {
          tapped = true;
        });
      },
      onTapUp: (_) {
        setState(() {
          tapped = false;
        });
      },
      child: Icon(
        Icons.indeterminate_check_box,
        color: tapped
            ? kSelectedIconColor
            : kAppbarColor,
        size: 40.0,
      ),
    );
  }
}

Upvotes: 3

Related Questions