How to implement a GestureDetector in Flutter?

Flutter does provide common widgets handling tap, such as IconButton. But sometimes, you need to detect gestures on a custom view: here comes GestureDetector!

How to add a GestureDetector

To follow the code tutorial, create a new app as follows.

If you’re unsure how to set up a Flutter app, check out Getting started with Flutter official tutorial.

In main.dart, we launch the app as below.

This won’t build until we create HomePage. So let’s create a new folder home in lib folder, and add the file home_view.dart to it. Let’s add some UI code, to display a line of text, an icon, and another line of text, all of it with a red background.

We assume now that we want the whole red section to be clickable, so let’s add a GestureDetector.

 

Display touch feedback when tapping a GestureDetector

The GestureDetector offers different handles for each touch state. To show visual feedback when the user taps the view, we are going to render the background of the GestureDetector’s child based on the touch state. We will use a boolean to track whether a tap gesture is in progress.

 

Voila! We are now handling touch, and displaying touch feedback, when a user taps anywhere on the red section.

 

Enjoying this code tutorial? Support the blog!

Options
 

What next?

Check out the full list of currently supported gestures in Flutter.

 

Subscribe to my mailing list

Receive a monthly email with a curated list of the best 5 articles on software development I have come across during the month, as well as relevant blog updates such as new posts. The email is sent near the start of each month.
* indicates required

Android app developer with 8 years experience, ranging from start ups to large tech (Google) and non tech (British Airways) companies. Currently freelancing and learning Flutter. LinkedIn natalie ( at ) cogitas (dot) net

Author: Natalie Masse Hooper

Android app developer with 8 years experience, ranging from start ups to large tech (Google) and non tech (British Airways) companies. Currently freelancing and learning Flutter. LinkedIn natalie ( at ) cogitas (dot) net

1 thought on “How to implement a GestureDetector in Flutter?”

Leave a Reply

Your email address will not be published. Required fields are marked *