虽然inputFormatters是真实的,解释得很好,here很有魅力,但我想让用户知道他的输入发生了什么。应该显示一个简单的snackBar或其他对话框,提示用户:“由于不允许的标志,您的代码被修剪了。您只允许输入数字和字母!”
我的示例代码显示了对数字和字母的限制:TextFormField( inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.allow( RegExp("[0-9a-zA-Z]"), ), ],,如果用户粘贴一个包含其他符号的字符串,它们将被自动删除,但是用户可能看不到,所以我想给他显示一个警告。
我相信所有的帮助。
发布于 2022-04-01 12:13:34
谢谢你的回答,但我自己解决了,具体如下:
inputFormatter阻塞所有不允许的标志,不会在textController的onChanged值中显示它们,但是onChanged函数被触发并保持不变。因此,我向onChanged添加了以下代码:函数:
onChanged: (val) {
if (count == val.length) {
showSnackBar(
context,
'You entered an unallowed sign!',
icon: Icons.warning_outlined, // this is from my own class showSnackBar which shows a Row with an optional Icon
);
}
count = val.length; 每次用户键入不允许的签名时,都会弹出此警告,因为Text控制器发生了更改,但其值保持不变。
如果有零件,我可以做得更好,请评论,我会纠正它们。
TextFormField的完整代码,包括inputFormatters:首先,我创建了一个变量int计数= 0;
TextFormField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(
RegExp("[0-9a-zA-Z]"),
),
],
obscureText: false,
controller: _controller,
decoration: InputDecoration(
labelText:
'title',
),
onChanged: (val) {
if (count == val.length) {
showSnackBar(
context,
'Unallowd sign typed in!',
icon: Icons.warning_outlined,
);
}
model.textChanged(val);
count = val.length;
},
),谢谢
https://stackoverflow.com/questions/71697880
复制相似问题