在TextField后面提到keyboardType: TextInputType.number还可以使用逗号(,) 和其他特殊字符。所以我想阻止输入特殊字符,并且只允许在开头使用连字符(-)。
//valid entries
10
10.0
-10
-10.0
.01
//Invalid Entries
10.0.2
10-0
10.0-
Run Code Online (Sandbox Code Playgroud)
我试图用这个来实现
var expression = RegExp('([-]?)([0-9]+)([.]?)([0-9]+)');
TextField(
keyboardType: TextInputType.number,
inputFormatters: [WhitelistingTextInputFormatter(expression)],
controller: _answer,
}
Run Code Online (Sandbox Code Playgroud)
但它对我不起作用。所以我尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
小智 1
“^-?\d ” *
使用此正则表达式
inputFormatter: FilteringTextInputFormatter.allow(new RegExp("^-?\\d*")),
Run Code Online (Sandbox Code Playgroud)