Sub topic 10
Exposing swipe and long-press gestures as custom actions
Assume you know basic Dart, Flutter widgets, and stateful UI. A screen reader user cannot perform every gesture in the same way as a touch user. For example, a swipe may move focus instead of dismissing a row. A long press may have no obvious keyboard equivalent.
A custom semantics action is a named operation exposed through the screen reader's actions menu. The action calls the same callback as the touch gesture.
Map the gesture to an accessible action
Keep one callback for the operation, then connect that callback to both the gesture and the semantics action.
Semantics.customSemanticsActions accepts a map. Each key is a CustomSemanticsAction, and each value is the callback that runs when the user selects that action.
Semantics(
customSemanticsActions: {
const CustomSemanticsAction(label: 'Delete message'): _deleteMessage,
},
child: Dismissible(
key: ValueKey(message.id),
onDismissed: (_) => _deleteMessage(),
child: MessageTile(message: message),
),
)The action label should describe the result, such as “Delete message” or “Archive conversation”. Avoid labels such as “Swipe left”, because the user needs the operation, not the physical gesture.
Add a long-press alternative
The same approach works for a long press. The visible widget handles touch input, while Semantics exposes the operation to assistive technology.
class ArchiveButton extends StatelessWidget {
const ArchiveButton({
required this.onArchive,
super.key,
});
final VoidCallback onArchive;
@override
Widget build(BuildContext context) {
return Semantics(
customSemanticsActions: {
const CustomSemanticsAction(
label: 'Archive conversation',
): onArchive,
},
child: GestureDetector(
onLongPress: onArchive,
child: const Padding(
padding: EdgeInsets.all(16),
child: Text('Conversation'),
),
),
);
}
}A custom action does not replace a visible button when a button is appropriate. Prefer a standard IconButton, TextButton, or menu item when the operation should always be visible. Add a custom action when the touch design depends on a gesture or when the action is secondary.
Check common failure modes
- Do not expose an action that is unavailable in the current state. For example, hide “Undo” after the undo period ends.
- Give each action a short, unique label within its item.
- Keep the action safe to invoke more than once when possible. A screen reader user may repeat an action while learning the interface.
- After deleting or archiving an item, move focus or announce a useful result so the user knows what changed.
- Test on both TalkBack and VoiceOver. Their action menus and wording differ.
Exercise
A row is dismissed by swiping left. What should the custom semantics action be named, and which callback should it call?
Show answer
Name it after the result, such as “Delete message”, and connect it to the same callback used by the swipe handler.