确保 Flutter TextField 中仅输入有效的数字格式

问题描述 投票:0回答:1

我的 flutter 应用程序中有一个 TextField,可帮助输入计算器功能的数字。对于这个文本字段,我已将键盘设置为仅数字,使用

keyboardType: TextInputType.number

现在,这工作得很好,从某种意义上说,它确保只出现数字输入键盘。该键盘允许用户输入 0 到 9 的数字以及小数点。问题是,它并不能阻止用户输入多个小数点。一旦用户添加多个,该数字就会无效,计算器也无法工作。

本质上,我需要做的是确保用户只能输入1个小数点和数字,而不能输入其他字符。

我在这个论坛的另一个问题上遇到了

inputFormatters
功能,我尝试像这样使用它:

TextField(
 inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.allow(RegExp("[0-9].")),
  ], // Only numbers and a decimal point can be entered
),

虽然这确实有助于确保只输入数字和小数点,但它并不能阻止输入多个小数点,而应该只输入一个。

如何编辑此过滤规则,或者我还能做什么,以确保只能输入 1 位小数点,以确保数字始终采用正确的格式(即始终为整数或双精度)?

谢谢!

flutter double textfield inputformatter
1个回答
10
投票

您尝试过使用

DecimalTextInputFormatter
输入格式化程序吗?

TextFormField(
  inputFormatters: [DecimalTextInputFormatter(decimalRange: 1)],
  keyboardType: TextInputType.numberWithOptions(decimal: true),
)

您可以使用正则表达式和

FilteringTextInputFormatter
(按照您的方法)获得相同的结果,例如:

FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,1}')),

范围

{0,1}
就可以解决问题。

RegExp(r'^\d+\.?\d?')
对于这种情况也是有效的表达式。

更新(2024 年 4 月)

直接使用

FilteringTextInputFormatters
可以达到相同的结果:

FilteringTextInputFormatters.numbersOnly
© www.soinside.com 2019 - 2024. All rights reserved.