Flutter TextField如何禁止开头输入小数点并限制其仅输入一次
解决Flutter TextField的数字输入限制问题
直接给你两种可行方案,按需选择:
方案一:使用FilteringTextInputFormatter配合正则(简单快捷)
用FilteringTextInputFormatter.allow搭配精准正则,直接限制输入内容:
TextField( inputFormatters: [ // 只允许纯数字,或数字开头+单个小数点+可选数字,同时允许空输入 FilteringTextInputFormatter.allow(RegExp(r'^(\d+(\.\d*)?)?$')), ], keyboardType: TextInputType.numberWithOptions(decimal: true), )
这个正则的作用:
- 禁止以小数点开头
- 限制小数点最多出现一次
- 自动排除逗号、减号、空格(因为正则只允许数字和单个小数点)
方案二:自定义TextInputFormatter(更灵活可控)
如果需要更精细的输入控制,比如实时处理每一个输入字符,用自定义Formatter:
class DecimalTextInputFormatter extends TextInputFormatter { @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { // 先过滤掉逗号、减号、空格 String newText = newValue.text.replaceAll(RegExp('[-, ]'), ''); // 阻止开头输入小数点 if (newText.startsWith('.')) { return oldValue; } // 限制小数点只能出现一次 int dotCount = newText.split('.').length - 1; if (dotCount > 1) { int firstDotIndex = newText.indexOf('.'); newText = newText.substring(0, firstDotIndex + 1) + newText.substring(firstDotIndex + 1).replaceAll('.', ''); } return TextEditingValue( text: newText, selection: TextSelection.collapsed(offset: newText.length), ); } } // 使用示例 TextField( inputFormatters: [DecimalTextInputFormatter()], keyboardType: TextInputType.numberWithOptions(decimal: true), )
为什么你之前的修改没生效?
你用了FilteringTextInputFormatter.deny(RegExp("^.?\\d*")),问题出在:
- 正则里的
.是任意字符,你没转义成\.,逻辑完全错误 deny是拒绝符合正则的输入,这和你想要的“允许符合规则的输入”逻辑相反,应该用allow来限定合法输入范围,而非用deny去排除非法内容(很难覆盖所有情况)
内容的提问来源于stack exchange,提问作者FabioTambu
相关产品推荐
相关产品推荐

