美文网首页Flutter学习
flutter自定义TextInputFormatter,一个中

flutter自定义TextInputFormatter,一个中

作者: 三也视界 | 来源:发表于2021-09-03 22:33 被阅读0次
    class IgnoreOtherCn2Formatter extends TextInputFormatter{
    
      final int maxLength;
      IgnoreOtherCn2Formatter({this.maxLength = -1});
    
      int count;
      var _regExp=r"^[\u4E00-\u9FA5A-Za-z0-9_]+$";
      @override
      TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    
        int newValueLength = newValue.text.length;
        int count = 0;
        int oldValueLength = oldValue.text.length;
        if(newValueLength == 0){
          return newValue;
        }
        if(maxLength >0){
          for (int i = 0; i < newValueLength; i++) {
            if (newValue.text.codeUnitAt(i) > 122) {
              ///中文字符按照2个计算
              count++;
            }
            if(i >0 && count +i > maxLength-1){
              String text =newValue.text.substring(0,i);
              LogUtil.v("formatEditUpdate 0 maxLength:$maxLength i:$i   count:$count  text:$text  newValueLength:$newValueLength  oldValueLength:$oldValueLength oldValue:${oldValue.text}   newValue:${newValue.text}   ",tag: "IgnoreOtherFormatterCn");
              return newValue.copyWith(text:text,composing:TextRange.empty,selection: TextSelection.fromPosition(
                  TextPosition(offset: i,affinity: TextAffinity.downstream)));
            }
          }
        }
        LogUtil.v("formatEditUpdate maxLength:$maxLength count:$count  newValueLength:$newValueLength  oldValueLength:$oldValueLength oldValue:${oldValue.text}   newValue:${newValue.text}   ",tag: "IgnoreOtherFormatterCn");
        if(newValueLength>0 && RegExp(_regExp).firstMatch(newValue.text)!=null){
          if(newValueLength +count<= maxLength){
            return newValue;
          }
        }
        return oldValue;
      }
    }
    

    相关文章

      网友评论

        本文标题:flutter自定义TextInputFormatter,一个中

        本文链接:https://www.haomeiwen.com/subject/svvirltx.html