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,
) {
final String latin = newValue.text.toLatinNumber();
if (latin.startsWith("+") || latin.startsWith("00")) {
final String international = latin.replaceAll(RegExp(r"[^\d+]"), "");
return TextEditingValue(
text: international,
selection: TextSelection.collapsed(offset: international.length),
);
}
int typed = _digitsBefore(latin, newValue.selection.baseOffset);
String digits = _digitsOf(latin);
final bool deleted = newValue.text.length < oldValue.text.length;
if (deleted && digits == _digitsOf(oldValue.text.toLatinNumber()) && typed > 0) {
digits = digits.substring(0, typed - 1) + digits.substring(typed);
typed--;
}
final String limited = UPhoneNumberUtils.inputDigits(digits, countryCode: countryCode);
final String formatted = UPhoneNumberUtils.formatNational(limited, countryCode: countryCode);
final int target = typed - (digits.length - limited.length);
int offset = 0;
int seen = 0;
while (offset < formatted.length && seen < target) {
if (_isDigit(formatted[offset])) seen++;
offset++;
}
return TextEditingValue(
text: formatted,
selection: TextSelection.collapsed(offset: offset.clamp(0, formatted.length)),
);
}