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(),
],
),
Author by
Chris
Updated on December 29, 2022Comments
-
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 fromStrings
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?