DEV Community

Python Geeks
Python Geeks

Posted on • Originally published at pythongeeks.net on

How to make a clickable Container in Flutter

Many times while you are working in Flutter, you would like to allow onTap in the Container widget. However, the Container widget doesn’t have onTap or onPress method. So this post is exactly for you, at the end of this post we will know 2 ways to enable onTap method in a Container.

clickable Container in Flutter

By default, there is no onTap method in the Container widget. So it can make some developers, including me, confuse a lot because they don’t know how to make a clickable Container. I will introduce you 2 ways to do it easily:

  • Wrap Container with InkWell widget
  • Using GestureDetector to detect a click

Using InkWell widget to make a clickable Container

So what is InkWell? and how it can make a Container clickable? We will make it clear in this section.

In Flutter, InkWell is a material widget that responds to touch action.

Reference below code to see how to make a clickable Container with InkWell



InkWell(
child: Container(...),
onTap: () {
print("Tapped on container");
},
);

Enter fullscreen mode Exit fullscreen mode




GestureDetector widget to detect a gesture

As its name can show exactly the widget ability. GestureDetector is a widget that detects the gestures.

It means if we wrap the Container inside a GestureDetector, we can make a clickable Container.

Now use below syntax to do what you want and enjoy the resolve:



GestureDetector(
onTap: () {
print("Tapped a Container");
},
child: Container(...),
)

Enter fullscreen mode Exit fullscreen mode




Difference between 2 methods

We already know 2 methods to make a clickable Container. Now we try to point out the difference between it. So you can choose the most suitable method for your case.

  • InkWell is a material widget and it can show you a visual effect whenever a touch was received.
  • GestureDetector is more general-purpose, not only for touch but also for other gestures.
  • Sometimes you can experience an issue that GestureDetector can’t detect touch action on free space, only detect the touch on child widget of Container.

Conclusion

Now we can summarize 2 methods to make a Container clickable in Flutter:

  • Using InkWell widget to wrap the Container.
  • Detecting touch action by using GestureDetector.

In this scope of the post, we can’t show you more information about InkWell widget and GestureDetector widget. It’s highly recommended you find more information in the official document of Flutter:

How these 2 methods resolve your case? You can show us and other audiences in the comments of the post. Happy in programming!

The post How to make a clickable Container in Flutter appeared first on Python Geeks.

Top comments (2)

Collapse
 
emmanuelbit profile image
Emmanuel-BIT

Thank you!

Collapse
 
samvolton_eth profile image
Sam Dundar.eth

vayvay