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.


What next?

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


Author: Natalie Masse Hooper

Mobile app developer with 12 years experience. Started with the Android SDK in 2010 and switched to Flutter in 2017. Past apps range from start ups to large tech (Google) and non tech (British Airways) companies, in various sectors (transport, commercial operations, e-commerce).

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

Leave a Reply

Your email address will not be published.