问题描述
我正在创建一个电子邮件字段,我想避免或自动删除其中的前导和尾随空格.
I'm making an email field and I'd like to either avoid or auto-delete leading and trailing spaces in it.
我尝试使用
myTextFieldController.addListener(() { myTextFieldController.text = myTextFieldController.text.trim(); });
但是,只要用户键入任何字符,它就会将光标移到开头.
but as soon as the user types any character it moves the cursor to the beginning.
还有其他方法吗?
您认识用户,所以我需要将其删除,否则他们将永远呆在那里尝试验证该字段.
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.
推荐答案
您可以使用 TextField
的 inputFormatters
属性.它不允许用户在textField中添加空格.
You can use inputFormatters
properties of TextField
.It wont allow users to add spaces in textField.
TextField(
inputFormatters: [
BlacklistingTextInputFormatter(RegExp('[ ]')),
]
);
更新:对于高于1.20.*的Flutter版本,请改用此选项
UPDATE:For flutter version above 1.20.* use this instead
TextField(
inputFormatters: [
FilteringTextInputFormatter.deny(RegExp('[ ]')),
]
);
这篇关于有没有一种方法可以自动删除或避免TextField中的前导和尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!