Working with gestures is fairly simple as Flutter was designed to work in the mobile environment.
Let’s start by creating a basic Flutter app, the way we’ve done before. Then removing the comments and existing widgets so we’re left with a blank app.
The Simplest Gesture – the Tap
The onTap()
is very similar to the onPress()
event handler for other widgets, doing the same thing. Whether this will change in the future as the platform evolves, I don’t know. It does seem that buttons tend to have press events, while the GestureDetector
has tap events.
However, the GestureDetector
seem to be a few other features, so it’s not just about what to call it. For example, GestureDetector
has other event handlers such as:
- onTapDown
- onTapUp
- onSecondaryTap — click with right mouse button
- onDoubleTap — double click
- and more…
How you use those extra features is up to you and how you would use them. This gives a lot more flexibility and control to what you want to do. Let set this up real quick.
I’m going to put this in place of where the text widgets are in the default app.
GestureDetector(
// When the child is tapped, show a snackbar.
onTap: () {
const snackBar = SnackBar(content: Text('Tap'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
// The custom button
child: Container(
padding: const EdgeInsets.all(12.0),
decoration: BoxDecoration(
color: Colors.lightBlue,
borderRadius: BorderRadius.circular(8.0),
),
child: const Text('My Button'),
),
)
Notice I have a simple SnackBar
, a small popup at the bottom of the screen which will automatically disappear after a few seconds, which lets me know I “tapped”. We can update that so there is more events we check for with ease.
A Ripple When Tapped
Do you want a small visual effect built in when you tap on a button, then you will need to use the InkWell
widget. When it is tapped, a ripple effect occurs on the button.
// The InkWell wraps the custom flat button widget.
InkWell(
// When the user taps the button, show a snackbar.
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Tap'),
));
},
child: const Padding(
padding: EdgeInsets.all(12.0),
child: Text('Flat Button'),
),
)
InkWell
doesn’t have as many events to work with as GestureDetector
, but it does allow you to configure more colors to create greater effects.
Starting with Gestures in Flutter was originally found on Access 2 Learn