有没有办法自动删除或避免 TextField 中的前导和尾随空格? [英] Is there a way to automatically remove or avoid leading and trailing spaces in a TextField?

查看:18
本文介绍了有没有办法自动删除或避免 TextField 中的前导和尾随空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个电子邮件字段,我想避免或自动删除其中的前导和尾随空格.

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.

推荐答案

您可以使用 TextFieldinputFormatters 属性.它不允许用户在 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 中的前导和尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆