fluttercontrollertextfield

Is there a way to automatically remove or avoid leading and trailing spaces in a TextField?


I'm making an email field and I'd like to either avoid or auto-delete leading and trailing spaces in it.

I tried using

myTextFieldController.addListener(() { myTextFieldController.text = myTextFieldController.text.trim(); });

but as soon as the user types any character it moves the cursor to the beginning.

Any other way?

You know users so I need to remove it or they will stay there forever trying to validate the field.

Of course I know I can do it before validating but I'd like to know if there's a more robust approach.


Solution

  • You can use inputFormatters properties of TextField. It wont allow users to add spaces in textField.

    TextField(
            inputFormatters: [
                    BlacklistingTextInputFormatter(RegExp('[ ]')),
                  ]
    );
    

    UPDATE: For flutter version above 1.20.* use this instead

    TextField(
                inputFormatters: [
                        FilteringTextInputFormatter.deny(RegExp('[ ]')),
                      ]
        );