Flutter中如何实现TextField已有小数点后禁止再次输入小数点
实现方案
你现有代码的问题在于使用的正则[0-9.]仅做单字符校验,只要输入字符是数字或小数点就放行,未限制整个输入字符串的小数点数量,修改方法如下:
方法1:直接修改正则表达式(最简方案)
将FilteringTextInputFormatter.allow的正则替换为全局匹配规则,限制整个输入最多只能有1个小数点:
child: TextField( style: TextStyle(color: Colors.white), // 替换原inputFormatters配置即可 inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d*$'))], controller: controller, keyboardType: TextInputType.number, decoration: textDecorator, onSubmitted: (value) { //Some Action }, ),
- 正则说明:
^\d*\.?\d*$表示字符串从开头到结尾,只允许存在0或1个小数点,小数点前后均可匹配任意长度的数字,也兼容.123、123.这类输入场景。如果不需要支持开头/结尾为小数点,可以调整正则为RegExp(r'^\d+\.?\d*$')
方法2:自定义输入格式化器(灵活扩展)
如果后续需要额外限制小数位数、整数位数等规则,可以自定义TextInputFormatter实现更可控的校验:
class SingleDecimalFormatter extends TextInputFormatter { @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { // 新输入为空直接放行 if (newValue.text.isEmpty) { return newValue; } // 统计当前输入的小数点数量 int dotCount = newValue.text.characters.where((char) => char == '.').length; // 小数点数量超过1个时,回退到上一次的合法输入 if (dotCount > 1) { return oldValue; } return newValue; } }
使用时将自定义格式化器加入inputFormatters数组即可:
inputFormatters: [SingleDecimalFormatter()],
内容的提问来源于stack exchange,提问作者Hari
相关产品推荐
相关产品推荐

