GestureDetector on transparent Widgets
I've been using a GestureDetector
to detect taps on an icon. The problem is that unless I tapped exactly on the icon, it wouldn't detect the tap.
My first idea was to wrap the Icon
in a Container
with some padding:
return GestureDetector(
onTap: () {
...
},
child: Icon(Icons.bluetooth));
to
return GestureDetector(
onTap: () {
...
},
child: Container(
child: Icon(Icons.bluetooth),
padding: const EdgeInsets.all(16),
));
But that still did not work, even though I could see the extra padding was laid out properly. After a quick search, I found this post. In their example, they add a foregroundDecoration: BoxDecoration(color: Color.fromRGBO(155, 85, 250, 0.4))
to the container. Surprisingly, now the GestureDetector
did capture taps around the icon!
At the end of the post, one person suggested using an InkWell. It's the Widget
that is used to detect touch events and show the touch animation. Sounds fancy. I might try it some day. Someone else suggested setting the behavior
property of GestureBehavior
, and that's what I was looking for. Since I don't actually need the Container
's padding in the layout, the final code was:
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
...
},
child: Icon(Icons.bluetooth));