所以我正在制作一个聊天应用程序,我希望用户提交的用户名不应该是大写的,并且要有空格,我可以接受该名称,以后再在更改的功能中进行更改,但是我希望用户也知道它。
答案 0 :(得分:4)
Flutter的TextField
或TextFormField
具有名为inputFormatters
的属性,该属性包含TextInputFormatter
的列表。
TextInputFormatters
的示例对您的情况很有用。
FilteringTextInputFormatter.allow(RegExp("[a-z]"))
TextField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp("[a-z]")),
],
)
您可以在此处查看TextInputFormatters
API文档:Reference
(在颤动1.20之前):
WhitelistingTextInputFormatter(RegExp("[a-z]")),
TextField(
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter(RegExp("[a-z]")),
],
)
如果不清楚的话,可以作为参考:Reference 2,Reference 3。
也请查看此SOF问题:Reference 4
答案 1 :(得分:1)
您可以使用Form
,然后使用错误字段(验证程序)通知用户
TextFormField(
validator: (name) {
Pattern pattern = r'^[a-z]+$'; // Regex for lowercase only
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(name))
return 'Username must be lowercase, this will be changed when saved';
else
return null;
},
),
FlatButton(
child: Text('Save'),
onPressed: () {
_formKey.currentState.validate(); // just check if its valid and notify user
// Other code to save the and change the value
print('Saving Username');
},
)
答案 2 :(得分:0)
关于更改文本,请尝试执行以下操作:
让我们说“ s”是用户名:
String s = ""
onChange(val) {
s = val.trim().toLowerCase()
}
如果要通知用户,也许使用带有一些文本的警报对话框,让他们知道用户名不应为大写且不包含空格。无论如何,您不能假设用户将遵循他们的“应做”。
答案 3 :(得分:0)
注释:使用FilteringTextInputFormatter.allow
代替WhitelistingTextInputFormatter
。因为 v1.20.0-1.0.pre 之后不推荐使用此功能。 FilteringTextInputFormatter
。allow是类型Pattern,
这是使用方法
TextField(
inputFormatters: [
// is able to enter lowercase letters
FilteringTextInputFormatter.allow(RegExp("[a-z]")),
],
)
这意味着用户输入的任何文本均应小写