Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 73 ยท Input and forms

Gestures and Input Handling

Handle touch in Flutter with GestureDetector, InkWell, Draggable and Dismissible, and learn how hit testing and the gesture arena decide which widget wins.

Touch is how people use phones. A tap, a long press, a drag, a swipe, a pinch: Flutter turns raw pointer events into these higher-level gestures and routes them to your widgets. Most of the time you wrap a widget in GestureDetector or InkWell and write an onTap. But sooner or later two widgets want the same touch, such as a swipeable item inside a scrolling list, and you need to know how Flutter decides who wins.

This lesson covers the common gesture widgets, then explains the two mechanisms underneath: hit testing (which widgets are under the finger) and the gesture arena (which recognizer gets to act). Text fields and forms come next in Forms and validation.

Real vs stand-in. The Dart code is real Flutter code, read-only here. The live examples are JavaScript stand-ins of hit testing and of the gesture arena. They simplify the real framework to show the idea.

From finger to callback

Pointer events Down, move, up from the screen.
Hit test Which widgets are under the finger?
Arena Recognizers compete; one wins.
Callback Your onTap or onPanUpdate runs.
1 / 2

GestureDetector

GestureDetector listens for gestures on its child and draws nothing itself.

DART
GestureDetector(
  onTap: () => print('tap'),
  onDoubleTap: () => print('double tap'),
  onLongPress: () => print('long press'),
  child: Container(
    width: 120,
    height: 120,
    color: Colors.teal,
    alignment: Alignment.center,
    child: const Text('Touch me'),
  ),
)

Common callbacks: onTap, onDoubleTap, onLongPress, onPanStart/Update/End (free dragging in any direction), onHorizontalDragUpdate and onVerticalDragUpdate (one axis), and onScaleStart/Update/End (pinch and rotate; scale includes pan, so do not use both pan and scale on the same detector).

A dragging example, where details.delta is the movement since the last event:

DART
class DraggableDot extends StatefulWidget {
  const DraggableDot({super.key});

  @override
  State<DraggableDot> createState() => _DraggableDotState();
}

class _DraggableDotState extends State<DraggableDot> {
  Offset _position = const Offset(100, 100);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          left: _position.dx,
          top: _position.dy,
          child: GestureDetector(
            onPanUpdate: (details) => setState(() => _position += details.delta),
            child: const CircleAvatar(radius: 28, child: Icon(Icons.drag_indicator)),
          ),
        ),
      ],
    );
  }
}

(setState and the positioned Stack are covered in StatefulWidget and setState and the layout lessons.)

Hit-test behavior

By default a GestureDetector only reacts where its child actually paints. An empty Container with no color has no hit area, a classic surprise. Control this with behavior:

DART
GestureDetector(
  behavior: HitTestBehavior.opaque,   // the whole box counts, even transparent parts
  onTap: _select,
  child: const Padding(
    padding: EdgeInsets.all(24),
    child: Text('Whole padded area is tappable'),
  ),
)
  • deferToChild (default): only the child's painted area is hit.
  • opaque: the whole box is hit and nothing behind it can be.
  • translucent: the whole box is hit, and widgets behind it can also be hit.

InkWell and buttons

GestureDetector gives no feedback. Material users expect a ripple. InkWell provides it, but it must sit on a Material ancestor (a Card, Scaffold body, or Material widget) and the colors it draws appear on that material, so a colored Container between them hides the ripple.

DART
Card(
  clipBehavior: Clip.antiAlias,
  child: InkWell(
    onTap: () {},
    child: const Padding(
      padding: EdgeInsets.all(16),
      child: Text('Tap for a ripple'),
    ),
  ),
)

If you only need a button, use the ready-made ones (Material tour); they already handle focus, hover, keyboard activation and screen readers. A bare GestureDetector does not, so wrap custom tappables in Semantics (see Accessibility and internationalization), and keep tap targets at least 48 by 48 logical pixels.

Draggable and DragTarget

Draggable lets a widget be picked up and carried; DragTarget accepts it.

DART
Draggable<String>(
  data: 'apple',
  feedback: const Material(child: Chip(label: Text('apple'))),   // shown under the finger
  childWhenDragging: const Opacity(opacity: 0.3, child: Chip(label: Text('apple'))),
  child: const Chip(label: Text('apple')),
)

DragTarget<String>(
  onWillAcceptWithDetails: (details) => details.data != 'banana',
  onAcceptWithDetails: (details) => setState(() => basket.add(details.data)),
  builder: (context, candidates, rejected) {
    return Container(
      height: 120,
      color: candidates.isEmpty ? Colors.grey.shade200 : Colors.green.shade100,
      alignment: Alignment.center,
      child: Text('Basket: ${basket.join(", ")}'),
    );
  },
)

The generic type on both sides (<String>) must match. candidates is non-empty while a drag hovers over the target and onWillAccept says yes; use it to highlight the drop zone. In a scrolling screen, use LongPressDraggable so a normal swipe still scrolls.

Dismissible

Dismissible makes a list item swipeable. It needs a unique key, because the list must know which item was removed (see Keys and widget identity).

DART
ListView.builder(
  itemCount: tasks.length,
  itemBuilder: (context, index) {
    final task = tasks[index];
    return Dismissible(
      key: ValueKey(task.id),
      direction: DismissDirection.endToStart,
      background: Container(
        color: Colors.red,
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 16),
        child: const Icon(Icons.delete, color: Colors.white),
      ),
      onDismissed: (_) {
        setState(() => tasks.removeAt(index));           // remove from the data NOW
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Deleted ${task.title}')),
        );
      },
      child: ListTile(title: Text(task.title)),
    );
  },
)

You must remove the item from your data inside onDismissed. If you do not, Flutter throws "A dismissed Dismissible widget is still part of the tree". Use confirmDismiss to show a dialog first.

Hit testing: who is under the finger?

When a finger touches down, Flutter performs a hit test: starting at the root, each render object checks if the touch point is inside its bounds, then asks its children, deepest first. The result is a list of render objects from the innermost widget up to the root. Events are sent to every entry of that list, in that order. In a Stack, children later in the list are painted on top and are tested first, so the topmost widget gets the touch.

Two widgets change this: IgnorePointer (the widget and its subtree become invisible to touch, but events pass through to widgets behind) and AbsorbPointer (it blocks touch for its subtree and for whatever is behind it). Disabling a whole form while it is submitting is a typical use of AbsorbPointer.

JS Hit testing a stack of boxes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The path starts with the innermost widget and ends at the root. The invisible overlay never appears, because IgnorePointer made it transparent to touch.

The gesture arena

Several widgets in the hit-test path may have gesture recognizers: a ListView listens for vertical drags, and a Dismissible inside it listens for horizontal ones. A recognizer cannot tell what the user means on the first pixel of movement. So each recognizer enters a gesture arena for that pointer, and they compete:

  • A recognizer wins by deciding the gesture is its own (a horizontal drag passes the drag slop of about 18 logical pixels in its direction), or by being the last one left.
  • A recognizer loses when it decides the gesture is not its own (a tap recognizer sees the finger move too far), or when another one wins.
  • Once one wins, all others are cancelled. For a tap, onTapCancel runs if the arena was lost.

This is why a horizontal swipe on a Dismissible row does not scroll the list, while a vertical swipe does. It is also why wrapping a button in a GestureDetector with onTap plus a scrolling parent works: a quick touch with no movement leaves the tap recognizer as the winner.

If you need a custom rule, RawGestureDetector with your own recognizers, or Listener for raw pointer events (no arena), are the lower-level tools. Ordinary apps rarely need them.

JS A tiny gesture arena

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A touch that barely moves ends with tap as the only recognizer left. A sideways swipe is claimed by the horizontal recognizer once it exceeds the slop, and the tap and vertical recognizers are cancelled.

Common mistakes

  • A GestureDetector around an empty or transparent box that never fires; set behavior: HitTestBehavior.opaque.
  • InkWell without a Material ancestor, or hidden by a colored Container, so no ripple shows.
  • Tap targets that are too small or not exposed to screen readers.
  • Using Dismissible without a unique key or without removing the data.
  • Nesting two same-direction scrollers or drags and wondering why one never moves.
  • Not disposing GestureRecognizers that you create yourself, for example for TextSpan.recognizer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why might a GestureDetector around an empty Container with no color never fire onTap?

    The default behavior defers to the child; an unpainted box has no hit area. opaque makes the whole box count.
  2. 2. What does the gesture arena decide?

    Recognizers enter the arena; one wins and the rest are cancelled.
  3. 3. What does a Dismissible require?

    The key tells Flutter which item left; you must remove it from the list data or Flutter throws an error.
  4. 4. Which widget lets touches pass through to widgets behind it while making its own subtree untouchable?

    IgnorePointer makes its subtree transparent to hit testing. AbsorbPointer blocks the touch for itself and for widgets behind.
  5. 5. Why use InkWell inside a Card instead of GestureDetector for a tappable tile?

    InkWell paints splash and highlight on the nearest Material. GestureDetector has no visual feedback.

Summary

  • GestureDetector handles taps, long presses, drags and scales with no visuals; InkWell adds a Material ripple.
  • Draggable/DragTarget move data between widgets, and Dismissible swipes items away (unique key, remove the data).
  • Hit testing finds the widgets under the finger, innermost first; HitTestBehavior, IgnorePointer and AbsorbPointer shape the result.
  • The gesture arena lets competing recognizers decide one winner, which is why horizontal swipes and vertical scrolling coexist.
  • Keep touch targets large, accessible and obvious to screen readers.

Next: Forms and Validation