Reputation: 3450
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
and toolbarOptions
but still I can copy and paste on the textfield in the web. Whats the solution for this. Thanks
TextFormField(
enableInteractiveSelection: false,
toolbarOptions: ToolbarOptions(
copy: false,
paste: false,
cut: false,
selectAll: false,
),
)
Upvotes: 3
Views: 2205
Reputation: 63569
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,
),
),
),
],
),
),
);
Upvotes: 4