Sub topic 13
Composing a custom tappable widget
Material buttons cover most actions. Sometimes a design needs something else, such as a tappable card, a list tile with a custom layout, or a tag chip. This chapter combines pieces from earlier chapters into one reusable widget. The widget shows ripple feedback, handles disabled state, meets the touch-target guideline, and reports itself correctly to screen readers.
It assumes you know StatelessWidget, GestureDetector callbacks, and the basics of InkWell and hit testing. It also assumes you have seen Semantics mentioned before.
Why not just wrap everything in GestureDetector?
GestureDetector recognizes gestures but gives no visual feedback and no keyboard or mouse behavior. A widget built on it alone has these gaps:
| Need | GestureDetector | InkWell inside Material |
|---|---|---|
| Tap, long press callbacks | Yes | Yes |
| Ripple and highlight feedback | No | Yes |
| Focus and Enter/Space activation | No | Yes |
| Hover and click cursor on desktop and web | No | Yes |
| Drag, pan, scale | Yes | No |
For a tappable surface, start from InkWell. Reach for GestureDetector when you need gestures InkWell lacks, such as pan or scale. You can also nest one inside the other.
The pieces and their order
The order of the wrappers matters. Each layer has one job.
- Semantics tells assistive technology that this is a button, whether it is enabled, and what it is called.
- Material is the surface where
InkWellpaints its splash. Without aMaterialancestor, no ripple appears. - InkWell recognizes taps and long presses and draws the feedback.
- ConstrainedBox enforces the minimum size, so the hit area is large enough.
A complete implementation
import 'package:flutter/material.dart';
class Tappable extends StatelessWidget {
const Tappable({
super.key,
required this.onTap,
required this.child,
this.onLongPress,
this.semanticLabel,
this.color,
this.borderRadius = const BorderRadius.all(Radius.circular(8)),
});
/// Pass null (and no onLongPress) to render the widget as disabled.
final VoidCallback? onTap;
final VoidCallback? onLongPress;
final Widget child;
/// Overrides the text a screen reader announces.
final String? semanticLabel;
final Color? color;
final BorderRadius borderRadius;
@override
Widget build(BuildContext context) {
final enabled = onTap != null || onLongPress != null;
return Semantics(
button: true,
enabled: enabled,
label: semanticLabel,
onTap: onTap,
onLongPress: onLongPress,
excludeSemantics: semanticLabel != null,
child: Material(
color: color ?? Colors.transparent,
borderRadius: borderRadius,
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
onLongPress: onLongPress,
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 48, minHeight: 48),
child: Center(
widthFactor: 1,
heightFactor: 1,
child: child,
),
),
),
),
);
}
}Here is a small app that uses it:
import 'package:flutter/material.dart';
import 'tappable.dart';
void main() => runApp(const DemoApp());
class DemoApp extends StatefulWidget {
const DemoApp({super.key});
@override
State<DemoApp> createState() => _DemoAppState();
}
class _DemoAppState extends State<DemoApp> {
int _likes = 0;
bool _locked = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Tappable(
color: Colors.teal.shade50,
semanticLabel: 'Like, $_likes so far',
onTap: _locked ? null : () => setState(() => _likes++),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text('Likes: $_likes'),
),
),
const SizedBox(height: 16),
Tappable(
onTap: () => setState(() => _locked = !_locked),
child: Icon(_locked ? Icons.lock : Icons.lock_open, size: 16),
),
],
),
),
),
);
}
}The second Tappable holds a 16-pixel icon, but its hit area is still 48 by 48. The first one becomes disabled, with no ripple, when _locked is true.
Design decisions in the implementation
Disabled state follows the callbacks
The widget has no separate enabled flag. Like Material buttons, it is disabled when its callbacks are null. This keeps one source of truth, so the visual state and the behavior cannot disagree. InkWell shows no splash when both onTap and onLongPress are null. The Semantics node reports enabled: false so a screen reader announces it as dimmed.
Padding goes inside the InkWell
Content padding belongs in the child that sits inside InkWell. Then the ripple and the hit area cover the padded region. Put Padding outside InkWell and the margin is dead space that ignores taps. Put Padding inside and the user can tap anywhere in the visible surface.
Color belongs to Material, not to Container
InkWell paints its ripple on the nearest Material ancestor. If you place a Container(color: ...) between Material and InkWell, the container paints over the ink and the ripple vanishes. The fix is to give the color to Material, as this widget does, or to use the Ink widget, which paints its decoration on the Material itself.
Clipping keeps the ripple inside the shape
InkWell paints a rectangular splash by default. With rounded corners, the splash would spill past them. Setting clipBehavior: Clip.antiAlias on Material together with borderRadius clips the ripple to the rounded shape. You can also set borderRadius on InkWell itself, which limits only the splash and does not clip the child.
Hit testing and the minimum size
A pointer event reaches a widget only if hit testing finds it under the pointer. The tappable region is therefore the size of the render object that receives the event. A 16-pixel icon alone gives a 16-pixel target.
Material guidelines call for touch targets of at least 48 by 48 logical pixels. Flutter's own buttons honor this through MaterialTapTargetSize. Your widget must enforce it by itself. ConstrainedBox with minimums does that. Center(widthFactor: 1, heightFactor: 1) shrinks to the child, then the parent's minimum constraint grows it to 48, which centers the icon within the larger area. Both the ripple and the hit area use the larger size.
Semantics: what assistive technology hears
Flutter builds a semantics tree beside the widget tree. InkWell already contributes a tap action, but not a role or a good label. The Semantics wrapper adds three things:
button: truetells the screen reader to announce "button".enabledreports whether the button can currently be activated.labelsupplies the spoken name. Without it, the framework uses the text of descendant widgets, and an icon has no text.
When you set a label, excludeSemantics: true hides the descendants' own semantics. Otherwise the screen reader reads the label and then the inner text, which duplicates. Because excluding descendants also removes the tap action that InkWell registered, the code passes onTap and onLongPress to Semantics directly. Activating the node through assistive technology then still runs your callbacks.
For icon-only content, prefer a visible Tooltip when sighted users would also benefit, as IconButton does. Tooltip adds both a long-press hint and a spoken label. You can wrap the whole Tappable in a Tooltip and skip the semanticLabel.
Testing the widget
Test the three guarantees: size, behavior, and semantics.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/tappable.dart';
void main() {
testWidgets('hit area is at least 48x48 and onTap fires', (tester) async {
var taps = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: Tappable(
onTap: () => taps++,
child: const Icon(Icons.add, size: 16),
),
),
),
),
);
expect(tester.getSize(find.byType(Tappable)), const Size(48, 48));
await tester.tap(find.byType(Tappable));
expect(taps, 1);
});
testWidgets('disabled widget ignores taps and reports disabled',
(tester) async {
final handle = tester.ensureSemantics();
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: Center(
child: Tappable(
onTap: null,
semanticLabel: 'Save',
child: Text('Save'),
),
),
),
),
);
final node = tester.getSemantics(find.byType(Tappable));
expect(node.label, 'Save');
expect(node.hasFlag(SemanticsFlag.hasEnabledState), isTrue);
expect(node.hasFlag(SemanticsFlag.isEnabled), isFalse);
handle.dispose();
});
}Replace my_app with your package name. ensureSemantics turns on semantics generation, which is off in tests by default. Dispose the handle at the end of the test.
Common errors
- No ripple: no
Materialancestor, or an opaqueContainerbetweenMaterialandInkWell. - Ripple square on a rounded shape:
MaterialhasborderRadiusbut noclipBehavior. - Dead margin around the content:
Paddingplaced outsideInkWell. - Screen reader reads the text twice: a label was set without
excludeSemantics. - Taps on transparent areas miss:
InkWellhit tests its child area, so aSizedBoxwith no child still needs a size, and aGestureDetectorover empty space needsHitTestBehavior.opaque.
Exercise
A teammate wraps a Tappable's content in Container(color: Colors.white) inside the InkWell, and the ripple stops appearing. The Material ancestor is present. Why does the ripple disappear, and what are two fixes?
Show answer
The ripple is painted on the Material, underneath its descendants. The opaque Container is a descendant of the Material and paints on top of the ink, so the ripple is hidden. Fix 1: remove the Container color and set the color on the Material (the color parameter of Tappable). Fix 2: replace the Container with an Ink widget (for example Ink(color: Colors.white, child: ...)), which paints its decoration on the Material itself so the ripple draws above it.
Exercise
A Tappable holds a 16-pixel icon. What size is its tappable area, and which line of the implementation produces it?
Show answer
The tappable area is 48 by 48 logical pixels. It comes from ConstrainedBox(constraints: BoxConstraints(minWidth: 48, minHeight: 48)) inside the InkWell. The Center with widthFactor and heightFactor of 1 shrinks to the icon, and the minimum constraints then grow the box to 48 by 48, so both the ripple and the hit area use that size.