Sub topic 10
Exposing swipe and long-press gestures as custom actions
This chapter assumes you can build Flutter layouts, write StatelessWidget and StatefulWidget classes, and use the Semantics widget to add labels. It also assumes you have run an app with TalkBack or VoiceOver at least once.
Why gestures need an alternative
Many Flutter interfaces hide operations behind gestures. Examples are swiping a message to delete it, long-pressing a photo to select it, or dragging a row to reorder it. Sighted touch users discover these by habit. A screen reader user cannot rely on them for three reasons:
- The screen reader changes how touch works. On both Android and iOS, a single swipe moves the focus to the next element, so your swipe never reaches the app. Dismissing a tile needs a special gesture that most users never learn.
- Nothing announces that the gesture exists. The screen reader reads the label of the tile, and it says nothing about swiping.
- Switch control, keyboard and voice users may not be able to perform a drag or a long press at all.
The fix is not to remove the gesture. Keep it for touch users and expose the same operation as a custom semantics action. A custom semantics action is a named command attached to a node in the semantics tree. The platform lists it in the screen reader's actions menu. On TalkBack this is the Actions option in the local context menu. On VoiceOver it is the Actions rotor.
How custom actions work
A CustomSemanticsAction has a label, which is the text the screen reader speaks and shows in the menu. You pass a map from each action to a callback in the customSemanticsActions parameter of Semantics.
Semantics(
customSemanticsActions: {
const CustomSemanticsAction(label: 'Delete message'): _deleteMessage,
},
child: Dismissible(
key: ValueKey(message.id),
onDismissed: (_) => _deleteMessage(),
child: MessageTile(message: message),
),
)When the user opens the actions menu on this tile, they hear "Delete message". Activating it calls _deleteMessage directly. The Dismissible is still there for touch users, and both paths run the same function.
Because the diagram fence must name its type, the flow is shown below.
A complete runnable example
The example below is a list of messages. Each row can be swiped away, and each row also exposes "Delete message" and "Mark as read" as custom actions.
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
void main() => runApp(const MaterialApp(home: InboxPage()));
class Message {
Message(this.id, this.title, {this.read = false});
final int id;
final String title;
bool read;
}
class InboxPage extends StatefulWidget {
const InboxPage({super.key});
@override
State<InboxPage> createState() => _InboxPageState();
}
class _InboxPageState extends State<InboxPage> {
final List<Message> _messages = [
Message(1, 'Meeting moved to 3 pm'),
Message(2, 'Your invoice is ready'),
Message(3, 'Weekend plans'),
];
void _delete(Message message) {
setState(() => _messages.removeWhere((m) => m.id == message.id));
}
void _markRead(Message message) {
setState(() => message.read = true);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inbox')),
body: ListView(
children: [
for (final message in _messages)
Semantics(
customSemanticsActions: {
const CustomSemanticsAction(label: 'Delete message'):
() => _delete(message),
const CustomSemanticsAction(label: 'Mark as read'):
() => _markRead(message),
},
child: Dismissible(
key: ValueKey(message.id),
onDismissed: (_) => _delete(message),
child: ListTile(
title: Text(message.title),
subtitle: Text(message.read ? 'Read' : 'Unread'),
),
),
),
],
),
);
}
}Run this with a screen reader on. Focus a row, then open the actions menu. You should see both actions listed.
Choosing good labels
The label is the whole interface for the screen reader user, so write it with care.
- Use a verb phrase that names the result, such as "Delete message" or "Pin conversation".
- Keep the label short. The user hears it every time they browse the menu.
- Do not include the gesture name. "Swipe to delete" is wrong, because the user is not swiping.
- Make labels specific when several rows repeat. The row's own label already tells which message the action applies to.
- Localize the label like any other user-visible string.
Long-press and other gestures
A long press has the same problem. Flutter exposes a dedicated semantics property for it. If you use onLongPress on a Semantics widget, the platform offers a long-press action on that node.
Semantics(
onLongPress: _enterSelectionMode,
onLongPressHint: 'Select this photo',
child: GestureDetector(
onLongPress: _enterSelectionMode,
child: PhotoTile(photo: photo),
),
)Many built-in widgets already do this. InkWell, ListTile with onLongPress, and Material buttons register their long-press handlers with the semantics tree. Only add onLongPress yourself when you build a custom gesture widget.
Use a custom action instead when there is no dedicated property. Reordering is the common case. A ReorderableListView offers "Move up" and "Move down" actions for you on its default drag handles. If you build your own drag-and-drop, add actions such as "Move up" and "Move down" that change the list order directly.
| Touch gesture | Built-in semantics property | Custom action needed |
|---|---|---|
| Tap | `onTap` | No |
| Long press | `onLongPress` | No, unless the widget is custom |
| Swipe to dismiss | `onDismiss` | Often yes, to name the result |
| Drag to reorder | None for custom widgets | Yes, "Move up" and "Move down" |
| Pinch to zoom | None | Yes, "Zoom in" and "Zoom out" |
| Swipe between pages | `onScrollLeft`, `onScrollRight` | Usually handled by scrollables |
Gotchas and common errors
Actions on the wrong node
Custom actions attach to the semantics node created by the Semantics widget. If the child produces its own focusable nodes, the action may end up on a parent that the screen reader never focuses. Wrap the whole row, not the whole list. If the row has several focusable children, merge them first so the row becomes one node.
Semantics(
customSemanticsActions: {
const CustomSemanticsAction(label: 'Delete message'): _deleteMessage,
},
child: MergeSemantics(
child: MessageTile(message: message),
),
)Duplicated actions
Some widgets already add actions. If you add "Delete message" and the tile also exposes a dismiss action through Dismissible, users may hear two similar choices. Check the actions menu on a real device after you add yours.
Actions that change the list
After a delete action runs, the focused node disappears. Screen readers then move focus to an unpredictable place. Where it matters, announce the result so the user knows what happened. The next chapter covers announcements in detail. Here is the short form:
void _delete(Message message) {
setState(() => _messages.remove(message));
SemanticsService.announce('Message deleted', TextDirection.ltr);
}SemanticsService lives in package:flutter/semantics.dart, and TextDirection comes from dart:ui, which package:flutter/widgets.dart re-exports.
Destructive actions
A screen reader user can trigger a custom action by accident, as easily as anyone can mis-tap. For irreversible operations, offer an undo, such as a snackbar with an Undo button, rather than a confirmation dialog on every row.
Testing custom actions
You can check that an action exists without a device. In a widget test, enable semantics, find the node, and perform the action.
import 'dart:ui';
import 'package:flutter/semantics.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/material.dart';
void main() {
testWidgets('inbox row exposes a delete action', (tester) async {
final handle = tester.ensureSemantics();
await tester.pumpWidget(const MaterialApp(home: InboxPage()));
final finder = find.bySemanticsLabel(RegExp('Meeting moved'));
final data = tester.getSemantics(finder).getSemanticsData();
expect(data.customSemanticsActionIds, isNotEmpty);
final id = CustomSemanticsAction.getAction(
data.customSemanticsActionIds!.first,
);
expect(id, isNotNull);
handle.dispose();
});
}This checks that at least one action is registered. Always follow it with a manual check, because only a real screen reader confirms that the menu is reachable and the label reads well.
Decision checklist
- List every gesture in the screen that is not a plain tap.
- For each one, ask whether a built-in semantics property already covers it.
- If not, add a
CustomSemanticsActionwith a verb label. - Make sure the callback is the same function the gesture calls.
- Open the actions menu with TalkBack and VoiceOver and listen to the labels.
Exercise
A Dismissible tile deletes an item when swiped. A TalkBack user focuses the tile and cannot delete it. What do you add, and what should the label be?
Show answer
Wrap the tile in a Semantics widget with customSemanticsActions containing a CustomSemanticsAction whose callback is the same delete function the swipe calls. Use a verb label such as "Delete item", not "Swipe to delete", because the user is choosing from a menu and not swiping.
Exercise
Why should the custom action and the gesture call the same function, and what should you do after the action removes the focused row?
Show answer
Sharing one function keeps both input paths behaving identically, so a fix or change applies to both. After the row is removed, the screen reader focus is lost, so announce the result (for example with SemanticsService.announce) and consider offering an undo.