Difference between HitTestBehavior.opaque and HitTestBehavior.translucent? (GestureDetector)

180 Views Asked by At
return GestureDetector(
    onTap: () => Navigator.of(context).pop(),
    child: GestureDetector(
      behavior: HitTestBehavior.translucent, <=== SEE HERE
      onTap: () {},
      child: child,
    ),
  );

I don't understand the difference between opaque and tanslucent. Based on my code both of them don't work

2

There are 2 best solutions below

0
Arthur Pellegrin On BEST ANSWER

The HitTestBehavior.translucent allows you to also trigger the Widget behind your top Z-Index widget. The HitTestBehavior.opaque will only trigger the top Z-index widget.

Imagine you have a Stack with two GestureDetector. the .opaque will trigger only the first one and the .translucent will trigger both.

I don't really understand why you need 2 GestureDetector here. Maybe try something like this:

return GestureDetector(
    onTap: () => Navigator.of(context).pop(),
    behavior: HitTestBehavior.translucent, <=== SEE HERE
    child: child
  );

In your code the 2 GestureDetector are listening to the same Gesture and only one will trigger the action. Here it's the second one who triggers the actions empty function

0
LagSeeing On

After many search I found that maybe HitTestBehavior only effect on Stack.

see issue #18450

Parent and child are not effect by HitTestBehavior, they are hitten both.

And in Stack, if your Container has color property, it is always opaque.

Container with translucent behavior should be with no color itself, like the issue say.

My test code is in follow

Listener(
      onPointerUp: (event) {
        print("Container");
      },
      child: Container(
        color: Colors.blue,
        child: Stack(
          children: [
            Listener(
              behavior: HitTestBehavior.translucent,
              onPointerUp: (event) {
                print("A");
              },
              child: Container(
                width: 100,
                height: 100,
                color: Colors.yellow,
              ),
            ),
            Positioned(
              left: 50,
              child: Listener(
                behavior: HitTestBehavior.deferToChild,
                onPointerUp: (event) {
                  print("B");
                },
                child: Container(
                  width: 100,
                  height: 100,
                  child: Center(
                    child: Container(
                      width: 10,
                      height: 10,
                      color: Colors.red,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    )