Copy and Paste not working in TextFormField & TextField in Flutter

6.8k Views Asked by At

Solved: COPY & PASTE Not Working in TextFormField

Found out that I was using Listener's onPointerDown Method to remove focus if the user clicks anywhere else in the App. But this was causing the error.

But the problem is now how to remove focus if anyone clicks somewhere else.

Listener(
    onPointerDown: (_) {
       FocusScopeNode currentFocus = FocusScope.of(context);
       if (!currentFocus.hasPrimaryFocus &&
       currentFocus.focusedChild != null) {
       currentFocus.focusedChild.unfocus();
      }
  },)

I'm trying to have Copy & Paste feature in the TextFormField in my Flutter app. I tried many ways but still, it's not working.


Here is my Code

Widget textFormWidget(
   String label, TextEditingController controller, bool enabled) {
return Padding(
  padding: const EdgeInsets.all(8.0),
  child: TextFormField(
    enabled: true,
    enableInteractiveSelection: true,
    readOnly: false,
    toolbarOptions:
        ToolbarOptions(paste: true, cut: true, selectAll: true, copy: true),
    textAlign: TextAlign.center,
    cursorColor: Colors.white,
    cursorWidth: 3,
    controller: controller,
    style: bold.copyWith(fontSize: 18),
    decoration: InputDecoration(
        focusColor: Colors.white,
        hoverColor: Colors.white,
        labelText: label,
        alignLabelWithHint: true,
        labelStyle: normal),
   ),
 );
}

Calling this as textFormWidget('Name', nameController, true),

If you need more code or information, please comment.

1

There are 1 best solutions below

0
On

I was also getting the same issue and was not able to copy and paste. So I removed

FocusScopeNode currentFocus = FocusScope.of(context);
       if (!currentFocus.hasPrimaryFocus &&
       currentFocus.focusedChild != null) {
       currentFocus.focusedChild.unfocus();
      }

part from onPointerDown , and to remove focus if anyone clicks somewhere else I wrap my MaterialApp with GestureDetector and added this :

 onTap: () => FocusManager.instance.primaryFocus?.unfocus(),

code :

GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: MaterialApp(
       //your code
      ),
    );