如何在textField中允许正负双精度-Flutter

时间:2019-06-11 09:05:53

标签: flutter dart

TextField中,提到keyboardType: TextInputType.number后,还可以使用comma(,)和其他特殊字符。因此,我想阻止键入特殊字符,并且也只允许在开头使用连字符(-)。

//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;
}

1 个答案:

答案 0 :(得分:0)

"^-?\d"*

使用这个正则表达式

inputFormatter: FilteringTextInputFormatter.allow(new RegExp("^-?\d")),