Flutter TextField 限制只允许输入数字,字母,小数,设置限制小数位数

TextField(
          inputFormatters: [
          //只允许输入字母
            WhitelistingTextInputFormatter(RegExp("[a-zA-Z]")),
          ],
   ),
    TextField(
    //只允许输入数字
          inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
   ),
    TextField(
      			inputFormatters: [
                          //只允许输入小数
                            WhitelistingTextInputFormatter(RegExp("[0-9.]")),
                          ],,
    TextField(
      			inputFormatters: [
                          //限制小数位数
                            _MyNumberTextInputFormatter(digit:5),
                          ],// 限制小数位数
class _MyNumberTextInputFormatter extends TextInputFormatter {
  static const defaultDouble = 0.001;
  ///允许的小数位数,-1代表不限制位数
  int digit;
  _MyNumberTextInputFormatter({this.digit=-1});
  static double strToFloat(String str, [double defaultValue = defaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }
  ///获取目前的小数位数
  static int getValueDigit(String value){
    if(value.contains(".")){
      return value.split(".")[1].length;
    }else{
      return -1;
    }
  }


  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value != ""
        && value != defaultDouble.toString()
        && strToFloat(value, defaultDouble) == defaultDouble
        ||getValueDigit(value)>digit) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }
    return new TextEditingValue(
      text: value,
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章