我需要限制用户何时输入 1.. 像这样。我正在使用文本输入表单字段。我需要像 1.23 这样的带有十进制输入文本格式器的输入
Cra*_*Cat 11
We can create our own TextInputFormatter
.
Check this
import 'package:flutter/services.dart';
class DecimalTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final regEx = RegExp(r"^\d*\.?\d*");
String newString = regEx.stringMatch(newValue.text) ?? "";
return newString == newValue.text ? newValue : oldValue;
}
}
Run Code Online (Sandbox Code Playgroud)
Usage:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstPage(),
debugShowCheckedModeBanner: false,
);
}
}
class FirstPage extends StatefulWidget {
@override
_FirstPageState createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextField(
inputFormatters: [DecimalTextInputFormatter()],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 9
不推荐使用 WhitelistingTextInputFormatter
TextField(
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d*')),
], // Only numbers can be entered
),
Run Code Online (Sandbox Code Playgroud)
正如用户 @ZaH 提到的,WhitelistingTextInputFormatter
从 Flutter 1.20 开始已被弃用,而FilteringTextInputFormatter.allow()
应该使用。在这里查看 ZaH 的答案并给他们点赞。您可以找到该类和构造函数的文档。
TextFormField(
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r"\d+([\.]\d+)?")),
],
);
Run Code Online (Sandbox Code Playgroud)
以下是您需要针对特定用例执行的操作:
TextFormField(
inputFormatters: [
WhitelistingTextInputFormatter(RegExp(r"\d+([\.]\d+)?")),
],
);
Run Code Online (Sandbox Code Playgroud)
你需要使用TextInputFormatter
类。特别是WhitelistingTextInputFormatter。
上面的代码仅允许您在问题中提供的模式的数字。可以选择任意位数的小数位数(允许有一位小数点)。
r
字符串前面的前缀使r""
字符串成为 a raw string
。这可以防止过滤和处理字符串中的特殊字符。来自文档:
请注意上面示例中使用的原始字符串(以 r 为前缀的字符串)。使用原始字符串将字符串中的每个字符视为文字字符。
这是正则表达式模式的剖析^\d+([\.]\d+)?$
:
\d
数字——允许所有语言的数字。+
一次或多次出现。(PATTERN)?
出现零次或一次——这允许数字没有小数点/数字。[\.]
允许点字符 - \ 用于转义它,因为它是正则表达式中的控制字符。 归档时间: |
|
查看次数: |
6302 次 |
最近记录: |