Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite Paste Event for TextFormField

Tags:

flutter

paste

I have a TextFormField. Usually you can use the selection toolbar to copy/paste/select all and so on using long tap/double tap.

I want to overwrite the Paste Event. It shouldn't simple insert the current clipboard data but open a popup with several options to insert.

Is it possible to catch and overwrite the Paste event in any way? I saw something like handlePaste() for SelectionControls, but I don't know how to add this to my TextFormField.

Thanks in advance!

like image 720
S-Man Avatar asked Jul 10 '26 10:07

S-Man


1 Answers

Since flutter 3.7 @Arenukvern answer is deprecated. Instead, toolbar events can be overwritten using contextMenuBuilder:

TextFormField(
    ...
    /// Override default input action toolbar to catch paste event
    contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) {
        return AdaptiveTextSelectionToolbar.editable(
            anchors: editableTextState.contextMenuAnchors,
            clipboardStatus: ClipboardStatus.pasteable,
            // to apply the normal behavior when click on copy (copy in clipboard close toolbar)
            // use an empty function `() {}` to hide this option from the toolbar
            onCopy: () => editableTextState.copySelection(SelectionChangedCause.toolbar),
            // to apply the normal behavior when click on cut
            onCut: () => editableTextState.cutSelection(SelectionChangedCause.toolbar),
            onPaste: () {
                // HERE will be called when the paste button is clicked in the toolbar
                // apply your own logic here

                // to apply the normal behavior when click on paste (add in input and close toolbar)
                editableTextState.pasteText(SelectionChangedCause.toolbar);
            },            
            // to apply the normal behavior when click on select all
            onSelectAll: () => editableTextState.selectAll(SelectionChangedCause.toolbar),
        );
    },
    ...
)

This should be compatible with all platforms except web (source)

like image 185
legoffmael Avatar answered Jul 14 '26 05:07

legoffmael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!