Flutter输入框如何限制小数点输入 标题已优化为BBS论坛风格

【求助】Flutter输入框怎么限制只能输入数字和小数点?

在开发记账APP时遇到问题:使用TextField做金额输入,需要限制用户只能输入数字和1位小数点(比如"12.5"),但输入"12.5.6"或"abc"时要自动过滤。试过inputFormatters但无法完全限制,求教各位大神有没有完整的解决方案?最好能附带小数点位数控制的代码示例~

2 回复

Flutter限制小数点输入,可通过TextField的inputFormatters实现。使用FilteringTextInputFormatter.allow(RegExp(r’^\d*.?\d{0,2}’))可限制最多两位小数。

更多关于Flutter输入框如何限制小数点输入 标题已优化为BBS论坛风格的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中限制输入框的小数点输入,可以通过以下两种常用方式实现:

1. 使用FilteringTextInputFormatter(推荐)

这是最简洁的方法,直接过滤掉非数字和小数点外的字符,并控制小数点数量:

TextField(
  inputFormatters: [
    FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')), // 限制最多两位小数
    // 或使用:FilteringTextInputFormatter.allow(RegExp(r'[0-9.]')), // 允许数字和小数点
  ],
  keyboardType: TextInputType.numberWithOptions(decimal: true),
)

2. 自定义TextInputFormatter

如需更精确控制(如单个小数点、首字符限制等):

class DecimalTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    // 空值直接允许
    if (newValue.text.isEmpty) return newValue;
    
    // 禁止首字符为小数点
    if (newValue.text == '.') return oldValue;
    
    // 匹配数字和单个小数点
    if (!RegExp(r'^\d*\.?\d*$').hasMatch(newValue.text)) {
      return oldValue;
    }
    
    // 限制单个小数点
    if ('.'.allMatches(newValue.text).length > 1) {
      return oldValue;
    }
    
    return newValue;
  }
}

// 使用
TextField(
  inputFormatters: [DecimalTextInputFormatter()],
  keyboardType: TextInputType.numberWithOptions(decimal: true),
)

补充说明

  • 设置keyboardType可调出数字键盘提升用户体验
  • 正则表达式r'^\d*\.?\d{0,2}'解释:
    • ^\d*:0个或多个数字开头
    • \.?:0个或1个小数点
    • \d{0,2}:最多2位小数

根据实际需求选择方案,第一种已能满足大部分场景。

回到顶部