我需要在TextField(inputFormatters:中插入什么?

我想在一个TextField中不允许\/,在另一个TextField中只允许aZ.

推荐答案

重要事项

services library中,你会发现TextInputFormatter abstract class(这意味着你必须导入package:flutter/services.dart).

它已经有了实现,有FilteringTextInputFormatter个(以前是BlacklistingTextInputFormatterWhitelistingTextInputFormatter)和LengthLimitingTextInputFormatter个.

如果您想实现自己的格式化程序,可以通过扩展TextInputFormatter本身并在其中实现formatEditUpdate来实现.

我将展示如何在给定的上下文中应用Premad FilteringTextInputFormatter.

示例

禁止\/

为此,我们将使用FilteringTextInputFormatter.deny constructor:

TextField(
  input重要事项: [
    FilteringTextInputFormatter.deny(RegExp(r'[/\\]')),
  ],
)

对于需要提供给格式化程序的Pattern,我将使用RegExp,即正则表达式.你可以找到更多关于here, which also links you to the features I will be using in my examples的信息.

在本例中,向双反斜杠\\和原始字符串(r'')支付attention.这实际上只代表了一个反斜杠.原因是反斜杠是RegExp中的转义键,所以如果我们想匹配\字符,我们需要使用两个反斜杠.我们甚至需要在没有原始字符串(r'')的情况下使用四个反斜杠,因为Dart也使用反斜杠作为转义键.使用原始字符串将确保Dart不会转义字符.


如果我们把它放到挡路ab0b03和.中,我们也会把它放在如下所示的列表[...]中:

FilteringTextInputFormatter.deny(RegExp('[abF!.]'))

这就是"deny/blacklist all 'a', 'b', 'F', '!' and '.'".

只允许aZ

这次我们使用FilteringTextInputFormatter.allow constructor:

TextField(
  input重要事项: [
    FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')),
  ],
)

为此,我们指定了两个字符范围:a-zA-Z,这也将接受这两个指定字符之间的所有字符(这里是所有字母).这也适用于0-9,您可以将任何字符附加到该列表中,例如,a-zA-Z0-9!.也会将!.考虑在内.

我们可以把这个结合起来

TextField(
  input重要事项: [
    FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')),
    FilteringTextInputFormatter.deny(RegExp('[abFeG]')),
  ],
)

这仅仅是为了说明input重要事项需要List<InputFormatter>,并且可以组合多个格式化程序.实际上,您可以使用一个允许/白名单和一个正则表达式来解决这个问题,但这也同样有效.

数字仅限

There are also already included static properties in the FilteringTextInputFormatter class: one of these is FilteringTextInputFormatter.数字仅限.
It will only accept/allow digits and is equivalent to an .allow(RegExp('[0-9]')) formatter.

Flutter相关问答推荐

将目标平台设置为Flutter 构建

在fltter_widget_from_html中启动url

如何将Will POP示波器转换为POP数据抖动的POP示波器

就像Flutter 中的头文件一样?

参数类型void Function()无法分配给参数类型void Function(LongPressEndDetails)?

在 Flutter 中使用条件语句设置 ImageProvider Object 类型的背景图像

如何将取消图标放置在右上角

如何使 flutter 2 手指zoom ?

如何更改 DropDownMenu 的显示方向?

从子类调用超类的超方法

Android Electric eel Mac M1:运行 flutter doctor -v 时无法找到Bundle 的 java 版本

我无法从 Cloud firestore 访问文档字段并在 statefulwidget 类中显示它

SfCircularChart 周围的额外间距

如何从 showModalBottomSheet 中的 topRight 和 topLeft 移除平边

如何使用 Row 和 Column 制作 L 形布局?

Flutter 在气泡聊天消息上对齐时间戳文本

如何在flutter中共享容器和gridview之间的滚动条?

Flutter Firebase:如何判断返回值是否是特定对象

Flutter ListView builder 未使用新数据更新

未处理的异常:FileSystemException:无法打开文件,路径 = 'assets/res.zip'(操作系统错误:没有这样的文件或目录,errno = 2)