Sub topic 8
Hit testing and HitTestBehavior
This chapter assumes you can use GestureDetector for taps and long presses, build layouts with Stack and Padding, and call setState. It explains how Flutter decides which widgets receive a pointer event, and how HitTestBehavior changes that decision. Many "my tap does nothing" bugs come from here.
What a hit test is
A hit test answers one question: which render objects are under this pointer? Flutter runs it when a pointer goes down, and for mouse hover and movement. It starts at the root of the render tree and walks down.
The walk produces a hit path, a list of render objects ordered from the deepest one up to the root. Flutter delivers the pointer down event to every entry in that path. It reuses the same path for the later move, up and cancel events of that pointer. A finger that slides off a button therefore still sends its events to the button, because the path was fixed at the moment of touch.
Two details in the diagram matter in practice:
- A box outside its own size is never hit, and its children are never asked. A child that overflows its parent, such as a
Positionedwidget placed outside aStack's bounds, cannot be tapped in the overflowing part. - Siblings are tested front to back, and the search stops at the first one that reports a hit. A box behind it is only tested if everything in front of it reported no hit.
The three behaviors
GestureDetector, Listener and several other widgets accept a behavior argument of type HitTestBehavior. The enum has three values.
| Value | Hit when | Widgets behind it |
|---|---|---|
| `deferToChild` | One of its children is hit | Can be hit wherever no child is hit |
| `opaque` | Anywhere inside its bounds | Cannot be hit inside its bounds |
| `translucent` | Anywhere inside its bounds (it joins the path) | Can still be hit inside its bounds |
GestureDetector uses deferToChild when it has a child. With no child it uses translucent.
translucent works because the box adds itself to the path but reports "no hit" to its parent, so the parent keeps testing the siblings behind it. If a child of a translucent box is hit, the box reports a hit and the search stops there. Translucent therefore only differs from deferToChild in the parts of the box that no child covers.
Seeing the behaviors
This app stacks a front GestureDetector over a back Listener. A Listener reports raw pointer events and takes no part in the gesture arena. Using it for the back widget shows which pointer events reach it without any competing tap recognizers.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
debugPrintHitTestResults = true;
runApp(const MaterialApp(home: Scaffold(body: HitTestDemo())));
}
class HitTestDemo extends StatefulWidget {
const HitTestDemo({super.key});
@override
State<HitTestDemo> createState() => _HitTestDemoState();
}
class _HitTestDemoState extends State<HitTestDemo> {
HitTestBehavior _behavior = HitTestBehavior.deferToChild;
int _frontTaps = 0;
int _backDowns = 0;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Column(
children: [
SegmentedButton<HitTestBehavior>(
segments: [
for (final b in HitTestBehavior.values)
ButtonSegment(value: b, label: Text(b.name)),
],
selected: {_behavior},
onSelectionChanged: (s) => setState(() => _behavior = s.first),
),
Text('front taps: $_frontTaps, back pointer downs: $_backDowns'),
SizedBox(
width: 200,
height: 200,
child: Stack(
children: [
Positioned.fill(
child: Listener(
behavior: HitTestBehavior.opaque,
onPointerDown: (_) => setState(() => _backDowns++),
child: const ColoredBox(color: Colors.indigo),
),
),
GestureDetector(
behavior: _behavior,
onTap: () => setState(() => _frontTaps++),
child: const SizedBox(
width: 200,
height: 200,
child: Center(
child: Text(
'front',
style: TextStyle(color: Colors.white),
),
),
),
),
],
),
),
],
),
);
}
}The SizedBox has no color and only a centered Text inside it. Only the text itself is hit through the child, and the rest of the 200 by 200 box is empty space. Tap once on the word and once on the empty area for each behavior. Each tap changes the counters as follows.
| Tap location | `deferToChild` | `opaque` | `translucent` |
|---|---|---|---|
| On the word "front" | Front tap | Front tap | Front tap |
| On empty space in the box | Back pointer down | Front tap | Front tap and back pointer down |
On the word, the child is hit and the search stops, so the back widget sees nothing in any mode. On empty space, deferToChild lets the tap fall through to the back widget, and opaque takes it for the front. translucent does both: the front joins the path and the back is still tested.
The debugPrintHitTestResults = true line in main prints the full hit path to the console on every pointer down. It is the quickest way to check which render objects were hit.
Translucent does not give two taps
Translucent lets the widgets behind receive raw pointer events. It does not make two tap callbacks fire for one tap. If the widget behind is also a GestureDetector with onTap, both tap recognizers join the gesture arena, and the arena picks one winner. In practice that is usually the frontmost widget, which is the first entry in the path. Chapter 11 covers the arena. For now, use Listener when you need raw events from a widget behind another one.
Other widgets that change the hit path
Some widgets alter hit testing without changing how anything looks.
| Widget | Effect on hit testing |
|---|---|
| `IgnorePointer` | Neither it nor its subtree is hit, so widgets behind can be |
| `AbsorbPointer` | Its subtree is not hit, but the box itself is, so widgets behind are blocked |
| `Offstage` | Hidden children are not hit |
| `Opacity` with 0.0 | Invisible but still hit, unlike `Offstage` |
| `Transform` | Hit positions are mapped through the inverse transform, so a rotated button is tapped where it is drawn |
| `Visibility` with `visible: false` | Not hit unless `maintainInteraction` is true |
The most common use is a decorative overlay, such as a gradient laid over a list. Wrap it in IgnorePointer, or taps on the list under it will be blocked.
Stack(
children: [
ListView(children: [for (var i = 0; i < 30; i++) ListTile(title: Text('Row $i'))]),
const Positioned(
left: 0,
right: 0,
top: 0,
height: 48,
child: IgnorePointer(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.white, Color(0x00FFFFFF)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
),
),
),
],
)Without IgnorePointer, the DecoratedBox is hit in its top 48 pixels, because decorated boxes report hits inside their bounds. The rows under it would no longer respond to taps.
Common errors
- A tap area is smaller than it looks. A
GestureDetectoraround aRowwithSpaceror padding only responds on the children. Useopaque. - A button in an overflowing
Positionedwidget cannot be tapped. The parentStackrejects positions outside its size before it tests any child. Enlarge theStackor move the widget inside it. - A full-screen detector blocks everything under it. An
opaquedetector over the whole page stops all widgets behind it from being hit. Usetranslucentif the page behind must stay usable. - Two overlapping detectors use the wrong one. The front sibling is tested first. If it reports a hit, the one behind never learns about the pointer.
- A disabled-looking overlay still lets taps through. Dimming with
Opacityor a semi-transparent color does not block hits. UseAbsorbPointerto block them.
Exercise
A GestureDetector with onTap wraps a Container(width: 100, height: 100) that has no color and no child. The detector has no behavior argument. Taps inside the square do nothing. Name two different changes that fix it.
Show answer
The detector uses deferToChild, and the empty Container reports no hit, so nothing in the detector's subtree is hit. Fix 1: set behavior: HitTestBehavior.opaque (or translucent) on the GestureDetector, so it joins the path itself. Fix 2: give the Container a color, such as Colors.transparent, so it paints a decorated box that reports a hit inside its bounds.
Exercise
In the demo app, you select translucent and tap on the empty space in the front box. What do the counters show, and why does tapping on the word "front" give a different result for the back counter?
Show answer
Both counters go up by one. The translucent front detector joins the hit path, so it receives the tap, but it reports no hit to the Stack, so the Stack goes on to test the back Listener, which also joins the path. On the word, the Text child is hit, so the front detector reports a hit and the Stack stops searching. The back Listener is never tested, so its counter does not change.