formatEditUpdate method
Called when text is being typed or cut/copy/pasted in the EditableText.
You can override the resulting text based on the previous text value and the incoming new text value.
When formatters are chained, oldValue
reflects the initial value of
TextEditingValue at the beginning of the chain.
Implementation
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
var newValueLength = newValue.text.length;
var count = 0;
if(newValueLength == 0){
return newValue;
}
if(maxLength >0){
for (var i = 0; i < newValueLength; i++) {
if (newValue.text.codeUnitAt(i) > 122) {
///中文字符按照2个计算
count++;
}
if(i >0 && count +i > maxLength-1){
var text =newValue.text.substring(0,i);
return newValue.copyWith(text:text,composing:TextRange.empty,selection: TextSelection.fromPosition(
TextPosition(offset: i,affinity: TextAffinity.downstream)));
}
}
}
if(newValueLength>0 && RegExp(_regExp).firstMatch(newValue.text)!=null){
if(newValueLength +count<= maxLength){
return newValue;
}
}
return oldValue;
}