我需要在TextField(inputFormatters:
中插入什么?
我想在一个TextField
中不允许\和/,在另一个TextField
中只允许a到Z.
我需要在TextField(inputFormatters:
中插入什么?
我想在一个TextField
中不允许\和/,在另一个TextField
中只允许a到Z.
在services library中,你会发现TextInputFormatter
abstract class(这意味着你必须导入package:flutter/services.dart
).
它已经有了实现,有FilteringTextInputFormatter
个(以前是BlacklistingTextInputFormatter
和WhitelistingTextInputFormatter
)和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不会转义字符.
如果我们把它放到挡路a
b
0b
03和.
中,我们也会把它放在如下所示的列表[...]
中:
FilteringTextInputFormatter.deny(RegExp('[abF!.]'))
这就是"deny/blacklist all 'a', 'b', 'F', '!' and '.'".
只允许a到Z
这次我们使用FilteringTextInputFormatter.allow
constructor:
TextField(
input重要事项: [
FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')),
],
)
为此,我们指定了两个字符范围:a-z
和A-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.