When users are reading comments or chat messages in your app, they may want to copy certain parts of it.
The Text widget doesn’t have selection built-in, which means a user can’t long-press to start text selection or double tap to select an individual word.
Instead, we have to use a widget called SelectableText (docs).
SelectableText(
'This is selectable text',
style: TextStyle(fontSize: 28);
// ...
) SelectableText also lets us define onSelectionChanged and contextMenuBuilder.
onSelectionChanged fires when a user changes the selected text or cursor location. It gives us information on the selected indices (TextSelection) and reason for selection (SelectionCause).
contextMenuBuilder lets us build custom text selection toolbars with default and custom actions.
SelectableText(
text,
style: TextStyle(fontSize: 28),
onSelectionChanged: (selection, cause) =>
print('onSelectionChanged: $selection, $cause'),
contextMenuBuilder: (context, editableTextState) =>
AdaptiveTextSelectionToolbar.buttonItems(
anchors: editableTextState.contextMenuAnchors,
buttonItems: editableTextState.contextMenuButtonItems
..add(
ContextMenuButtonItem(
onPressed: () {
print('Custom Button Tapped!');
editableTextState.hideToolbar();
},
label: 'Custom Button',
),
),
),
) And here’s the result!
