Flutter Don't allow leading whitespaces in TextField

1,691

Create your own TextInputFormatter and change returned value of formatEditUpdate(...).

Sample:

class NoLeadingSpaceFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.text.startsWith(' ')) {
      final String trimedText = newValue.text.trimLeft();

      return TextEditingValue(
        text: trimedText,
        selection: TextSelection(
          baseOffset: trimedText.length,
          extentOffset: trimedText.length,
        ),
      );
    }

    return newValue;
  }
}

Usage:

TextField(
  inputFormatters: [
    NoLeadingSpaceFormatter(),
  ],
),
Share:
1,691
Chris
Author by

Chris

Updated on December 29, 2022

Comments

  • Chris
    Chris over 1 year

    I have a simple TextField where the user should not be allowed to type in leading whitespaces. I found a couple of similar answers about removing whitespaces from Strings or don't allow any whitespaces. But in my case the only restriction should be leading whitespaces.

    This is what I found for TextFields but that is removing all whitespaces.

    Can anyone help me out here?