Flutter Web - TextFormField disable copy and paste
439
If you are considering of shortcut keyboards, we need to listen LogicalKeySet
.
Result
I've done this way:
For copy-paste keys
///* for mac replace LogicalKeyboardKey.control, with LogicalKeyboardKey.meta
final selectableKeySetwindows = LogicalKeySet(
LogicalKeyboardKey.control,
LogicalKeyboardKey.keyA,
);
final pasteKeySetwindows = LogicalKeySet(
LogicalKeyboardKey.control,
LogicalKeyboardKey.keyV,
);
/// i dont have any ios device 😅,let me know what it produce.
final selectableKeySetMac = LogicalKeySet(
LogicalKeyboardKey.meta,
LogicalKeyboardKey.keyA,
);
class SelectionIntent extends Intent {}
class PasteIntent extends Intent {}
The widget that will handle Events
class DisableShortcut extends StatelessWidget {
final Widget child;
const DisableShortcut({
Key? key,
required this.child,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return FocusableActionDetector(
shortcuts: {
selectableKeySetwindows: SelectionIntent(),
pasteKeySetwindows: PasteIntent(),
},
actions: {
SelectionIntent: CallbackAction(
onInvoke: (intent) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Copy is forbidden")));
return FocusScope.of(context).requestFocus(FocusNode());
},
),
PasteIntent: CallbackAction(
onInvoke: (intent) async {
// ClipboardData? data = await Clipboard.getData('text/plain');
// print(" paste callBack ${data!.text}");
return ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Paste is forbidden")));
},
)
},
autofocus: true,
child: child,
);
}
}
My testWidget
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(),
TextField(),
DisableShortcut(
child: TextField(
enableInteractiveSelection: false,
toolbarOptions: ToolbarOptions(
copy: false,
cut: false,
paste: false,
selectAll: false,
),
),
),
],
),
),
);
Author by
Raine Dale Holgado
BS in Computer Engineering, graduated from Silliman University. Interested in Web/Mobile development and Dart/Flutter. Love to explore new technology.
Updated on December 31, 2022Comments
-
Raine Dale Holgado over 1 year
I want to disable the copy and paste functionality on my textfield but unfortunately it didn't work as expected on the web. I tried the following
enableInteractiveSelection
andtoolbarOptions
but still I can copy and paste on the textfield in the web. Whats the solution for this. ThanksTextFormField( enableInteractiveSelection: false, toolbarOptions: ToolbarOptions( copy: false, paste: false, cut: false, selectAll: false, ), )
-
Raine Dale Holgado over 2 yearsNice. This would do for the meantime. Thanks