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



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