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;
}
}
网友评论