In Flutter, you can make any widget tappable by using the onTap
property. However, when it comes to a simple Container widget, things get a bit tricky. You can’t directly assign an onTap
callback to a Container. But don’t worry! There are ways to achieve this.
Option 1: Using InkWell
The first option is to wrap your Container in an InkWell
. The InkWell
widget is designed for creating tappable areas with a ripple effect, which is a visual cue when the user taps on it. This makes perfect sense when you think about how Material Design touch indicators work.
InkWell( child: Container(...), onTap: () { print("tapped on container"); }, )
As you can see, the InkWell
widget takes a callback function as its second argument, which will be called when the user taps on it. The callback is where you put your logic to handle the tap event.
Option 2: Using GestureDetector
The second option is to wrap your Container in a GestureDetector
. This widget provides a way to detect various types of gestures, including taps. Unlike the InkWell
, it doesn’t provide any visual feedback when the user taps on it.
GestureDetector( onTap: () { print("Container was tapped"); }, child: Container(...), )
The usage is similar to the InkWell, except that you don’t get a ripple effect. However, if you’re working with a non-Material Design theme, or simply want to avoid the visual effects altogether, then this might be a better choice.
Difference Between InkWell and GestureDetector
One thing to note is that there’s an important difference between the InkWell and the GestureDetector. While both can detect taps, only the InkWell will provide a ripple effect when the user interacts with it. If you want this visual cue for your tap event, then go with the InkWell.
If not, then you’re perfectly fine using the GestureDetector instead.