Sub topic 6
Detecting taps, double taps and long presses with GestureDetector
This chapter assumes you can build a widget tree with StatelessWidget and StatefulWidget, call setState, and read basic Dart closures. You should also know the layout widgets Row, Column, Stack and Padding. Buttons from earlier chapters already handle most tap needs. GestureDetector is the tool for everything else: arbitrary widgets, double taps, long presses and, in later chapters, drags.
What GestureDetector does
GestureDetector is a widget that wraps a child and listens for raw pointer events (touch, mouse, stylus). It does not draw anything. It feeds those events to gesture recognizers, small state machines that decide whether the events add up to a tap, a double tap, a long press and so on. When a recognizer decides it has a match, it calls the matching callback on your widget.
You enable a gesture by passing a callback. A recognizer is only created for callbacks you supply, so unused gestures cost nothing and do not compete for events.
The most common callbacks are:
| Callback | Fires when |
|---|---|
| `onTap` | The pointer goes down and up on the widget without moving far |
| `onTapDown` | The pointer touches the widget, before it is known to be a tap |
| `onTapUp` | The pointer lifts after a tap |
| `onTapCancel` | The pointer went down but the gesture was not a tap |
| `onDoubleTap` | Two taps happen in quick succession |
| `onLongPress` | The pointer stays down for about half a second |
| `onSecondaryTap` | A secondary button is clicked, such as a right mouse button |
A first example
The following widget reports a tap, a double tap and a long press:
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => debugPrint('tap'),
onDoubleTap: () => debugPrint('double tap'),
onLongPress: () => debugPrint('long press'),
child: const SizedBox(
width: 120,
height: 120,
child: Center(child: Text('Tap me')),
),
)The behavior: HitTestBehavior.opaque line makes the whole 120 by 120 box respond, including the empty areas around the text. Without it, a child with no painted content might not receive events. The next chapters on hit testing explain why. For now, treat opaque as the setting that makes the full bounds of the box tappable.
The life of a tap
A tap is a sequence of events, and the callbacks reflect that sequence. Knowing the order helps you choose between onTap and onTapDown.
- The pointer touches the screen.
onTapDownfires. - The pointer lifts without moving beyond a small slop distance.
onTapUpfires, thenonTap. - If the pointer moves too far, or another recognizer wins,
onTapCancelfires instead ofonTap.
Use onTap for actions, because it fires only when the user really completed a tap. Use onTapDown and onTapCancel together for immediate visual feedback, such as dimming a card while the finger is down.
Showing pressed feedback
This widget fades while pressed. It uses onTapDown to start the effect and onTapUp and onTapCancel to end it.
import 'package:flutter/material.dart';
class PressableCard extends StatefulWidget {
const PressableCard({super.key, required this.onTap});
final VoidCallback onTap;
@override
State<PressableCard> createState() => _PressableCardState();
}
class _PressableCardState extends State<PressableCard> {
bool _pressed = false;
void _setPressed(bool value) {
if (_pressed != value) setState(() => _pressed = value);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (_) => _setPressed(true),
onTapUp: (_) => _setPressed(false),
onTapCancel: () => _setPressed(false),
onTap: widget.onTap,
child: AnimatedOpacity(
opacity: _pressed ? 0.5 : 1.0,
duration: const Duration(milliseconds: 100),
child: const Card(
child: Padding(
padding: EdgeInsets.all(24),
child: Text('Press and hold me'),
),
),
),
);
}
}The _setPressed helper skips setState when nothing changes, which avoids needless rebuilds.
Callback details
Most callbacks receive a details object with the pointer position.
onTapDownreceivesTapDownDetails. It hasglobalPosition(relative to the screen) andlocalPosition(relative to the widget).onTapUpreceivesTapUpDetails, with the same two positions.onLongPressStartreceivesLongPressStartDetails. Related callbacks includeonLongPressMoveUpdateandonLongPressEnd, which let you track a finger that stays down after the long press begins.onTap,onDoubleTapandonLongPresstake no arguments.
For example, to place a marker where the user tapped:
GestureDetector(
onTapUp: (details) {
debugPrint('Tapped at ${details.localPosition}');
},
child: const SizedBox.expand(),
)Edge cases and common errors
onTap is delayed when onDoubleTap is also set
When a widget has both onTap and onDoubleTap, Flutter cannot fire onTap as soon as the first tap ends, because that tap might be the first half of a double tap. It waits for the double-tap timeout, about 300 milliseconds, before it decides. The user sees a lag on every single tap.
If you need an instant response, do not combine the two on the same widget. Either drop the double tap, or make the single-tap action harmless and reversible so that a delay is not needed. onTapDown fires immediately, but it also fires as the first half of a double tap, so use it only for feedback and not for actions.
A callback never fires
If nothing happens, check these causes in order:
- The detector's child has zero size or no hit area. Add
behavior: HitTestBehavior.opaqueor give it a sized child. - Another widget above it in the tree consumes the event. A
Stackchild painted on top of yours will receive the tap first. - The widget is inside an
IgnorePointerorAbsorbPointer. - A competing gesture, such as a scroll view's drag, wins. The gesture arena chapter covers this.
Tapping empty space does nothing
By default, GestureDetector uses HitTestBehavior.deferToChild. The detector responds only where its child is hit. A Container with only padding, or a Row with gaps between its children, leaves holes that ignore taps. Set behavior to HitTestBehavior.opaque to fill the holes.
No visual feedback
GestureDetector paints nothing. A user who taps gets no ripple, no highlight, and no hover cursor unless you add them yourself. For Material-style feedback, use InkWell, which is covered in its own chapter. Prefer a real button such as TextButton when the control is a button, because it also provides focus handling, keyboard activation and semantics.
Nested detectors
If two nested GestureDetector widgets both listen for taps, only the innermost one receives the tap. The outer detector's onTap does not fire. This is the result of the gesture arena, where one recognizer wins and the others are rejected.
GestureDetector(
onTap: () => debugPrint('outer'),
child: Container(
color: Colors.amber,
padding: const EdgeInsets.all(32),
child: GestureDetector(
onTap: () => debugPrint('inner'),
child: Container(width: 80, height: 80, color: Colors.deepOrange),
),
),
)Tapping the orange square prints inner only. Tapping the amber border prints outer.
Long press versus tap
A press that lasts longer than the long press timeout (about 500 milliseconds) becomes a long press, and onTap does not fire for it. If the user holds, then lifts, you receive onLongPress and onLongPressUp, but no tap.
Accessibility note
A GestureDetector does not tell screen readers that its child is interactive. A TalkBack or VoiceOver user may not find the control. Wrap it in Semantics with button: true and a label, or use a built-in button. A later chapter covers this in detail.
Choosing between GestureDetector and a button
| Need | Use |
|---|---|
| A labelled action with standard look | `FilledButton`, `ElevatedButton`, `OutlinedButton` or `TextButton` |
| An icon-only action | `IconButton` |
| A tappable card or list row with a ripple | `InkWell` or `ListTile` |
| Double tap, long press with movement, or no visuals | `GestureDetector` |
Summary of key points
GestureDetectorturns raw pointer events into callbacks and draws nothing itself.onTapfires on completion.onTapDownfires at first contact and is suited to feedback.- Pairing
onTapwithonDoubleTapdelays every single tap by roughly 300 ms. - Use
HitTestBehavior.opaquewhen empty areas should respond. - The innermost detector wins a tap, and a long press cancels the tap.
Exercise
A card has both onTap (opens a detail page) and onDoubleTap (marks it as a favorite). Users complain that opening the page feels slow. What causes the delay, and how could you remove it?
Show answer
Because onDoubleTap is registered, Flutter must wait about 300 ms after the first tap to see whether a second tap follows, and only then fires onTap. To remove the delay, drop onDoubleTap from the same widget (for example, move "favorite" to a separate IconButton or a long press), so onTap can fire as soon as the pointer lifts.
Exercise
You wrap a Row containing two Text widgets separated by a wide SizedBox in a GestureDetector with onTap. Tapping the gap does nothing. Which single property fixes this, and what value do you set?
Show answer
Set behavior to HitTestBehavior.opaque. The default deferToChild only responds where a child is hit, and the empty gap is not part of any child's hit area.