Detect swipes in Flutter!

Abhishek Doshi
3 min readAug 8, 2021

--

Want to navigate to screens based on user swipe? For example, if the user swipes left to right, navigate to the next screen and if the user swipes right to left, navigate to the previous screen. (Something similar to iOS 😉). Let’s see how you can do this!

Flutter framework provides an awesome widget and one of my favourite GestureDetector! It helps the developers to detect the interactions on a particular widget by a user. Let’s see how we can detect swipes.

To detect just a tap on the widget, we have onTap callback for that. Just wrap any widget with GestureDetector . Eg:

GestureDetector(
onTap: () {
print('Widget Tapped');
},
child: Container(),
),

onTap is really simple to use and is handy for the developers.

In GestureDetector , we have many callbacks which can be used for detecting swipes. However, there are 2 callbacks for horizontal and vertical swipes which are super easy to use and understand. These two are onHorizontalDragUpdate and onVerticalDragUpdate respectively. Let’s see how they work!

Let’s create a small app where on Page1 users can swipe from right to left to navigate to Page2. On Page2, users can swipe from left to right to pop the current page and navigate to Page1! (Something similar to iOS).

To detect right to left swipe, we can use onHorizontalDragUpdate as follows:

onHorizontalDragUpdate: (details) {
if (details.delta.direction > 0) {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Page2()));
}
},

However, you should also mention what to do if the user swipes vertically. Here, we won’t be doing anything, but we will be providing a blank function otherwise the gestures will collide.

onVerticalDragUpdate: (details) {},
onHorizontalDragUpdate: (details) {
if (details.delta.direction > 0) {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Page2()));
}
},

Now, here’s how our Page1 code looks like:

Now it’s time for detecting the swipe from right to left for Page2. Yes, you got it right, we just need to invert the condition!

onVerticalDragUpdate: (details) {},
onHorizontalDragUpdate: (details) {
if (details.delta.direction <= 0) {
Navigator.pop(context);
}
},

Here’s how Page2 code looks like:

Check out the entire project at: https://github.com/AbhishekDoshi26/swipe_detection_example

Now, let’s see this in action!! When you integrate this feature in your app, here’s how it will behave:

Hope you enjoyed this article!

If you loved it, you can Buy Me A Coffee!

Don’t forget to connect with me on:

Don’t stop, until you are breathing!💙
- Abhishek Doshi

--

--

Abhishek Doshi

Google Developer Expert — Dart, Flutter & Firebase 💙💛