在 TextField
提到后keyboardType: TextInputType.number
还可以使用逗号(,) 和其他特殊字符。所以我想阻止输入特殊字符,并且只允许在开头使用连字符(-)。
//valid entries
10
10.0
-10
-10.0
.01
//Invalid Entries
10.0.2
10-0
10.0-
我试图用这个来实现
var expression = RegExp('([-]?)([0-9]+)([.]?)([0-9]+)');
TextField(
keyboardType: TextInputType.number,
inputFormatters: [WhitelistingTextInputFormatter(expression)],
controller: _answer,
}
但它对我不起作用。所以我尝试使用
onChanged: answerOnChangeListener(_answer)
但它导致滞后answerOnChangeListener(TextEditingController controller) {
int oldLength = controller.text.length;
String newValue = stringMatch(controller.text);
if (oldLength != newValue.length) controller.text = newValue;
}
String stringMatch(String substring) {
String response = expression
.allMatches(substring)
.map<String>((Match match) => match.group(0))
.join();
print("stringMatch : $response");
return response;
}
最佳答案
"^-?\d"*
将此正则表达式与
inputFormatter: FilteringTextInputFormatter.allow(new RegExp("^-?\d")),
关于flutter - 如何在 textField 中允许正负双倍 - Flutter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56540139/