Flutter - change text opacity on press

Viewed 1124

Basically I want to change the opacity of the text when it is clicked. Like when it is pressed, its opacity becomes 0.4 and once it is released, its opacity becomes 1.0. Currently I'm trying to use AnimatedOpacity and I can only change the opacity on tap.

double textOpacity = 1.0;
//some widgets
 AnimatedOpacity(
   duration: const Duration(milliseconds: 100),
   opacity: textOpacity,
   child: GestureDetector(
     child: Text(
       'Tap',
       style: TextStyle(
          color: CupertinoColors.systemBlue,
       ),
     ),
     onTap: () {
       setState(() => textOpacity = 0.4);
     }
  ),
),

I also tried

onForcePressStart: (details) =>
    setState(() => textOpacity = 0.4),
onForcePressEnd: (details) =>
    setState(() => textOpacity = 1.0),

but it didn't work.

Can any one help me with it? Thanks!

2 Answers

As pointed out in the comments onTapDown() and OnTapCancel will do the job.

This is the code:


double opacity= 1.0; //Initialise for the first time Widget build.
GestureDetector(
              onTapDown: (TapDownDetails details) {
                opacity = 0.4;
                print('tappedDown');
                setState(() {});
              },
              onTapCancel: () {
                opacity = 1.0;
                print('tapcancel');
                setState(() {});
              },
              child: AnimatedOpacity(
                duration: Duration(milliseconds: 300),
                opacity: opacity,
                child: Text('Your Text'),
              ),
            )

There is ready-to-use solution:

CupertinoButton(
  onPressed: () {
    // any action
  },
  child: Text('Tap'),
)
Related