【问题标题】:How to allow positive and negative double in textField - Flutter如何在 textField 中允许正负双精度 - Flutter
【发布时间】:2019-10-25 15:58:37
【问题描述】:

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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    "^-?\d"*

    将此正则表达式用于

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多