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,
) {
if (newValue.text.isEmpty) {
return newValue;
}
if (allowNegative && newValue.text == '-') {
return newValue;
}
String textToFormat = newValue.text;
if (allowDecimals && textToFormat.startsWith('.')) {
textToFormat = '0$textToFormat';
}
final formatted = NumericFormatterUtils.formatNumberString(
textToFormat,
groupingSystem: groupingSystem,
allowDecimals: allowDecimals,
decimalPlaces: decimalPlaces,
allowNegative: allowNegative,
);
if (maxValue != null) {
final parsed = NumericFormatterUtils.parse(formatted);
if (parsed != null && parsed > maxValue!) {
return oldValue;
}
}
// Cursor position calculation
int cursorPosition = newValue.selection.end;
final oldDigitsBeforeCursor = newValue.text
.substring(0, cursorPosition.clamp(0, newValue.text.length))
.replaceAll(RegExp(r'[^\d.]'), '')
.length;
int newCursor = 0;
int digitsCount = 0;
for (int i = 0; i < formatted.length; i++) {
if (digitsCount >= oldDigitsBeforeCursor) break;
if (RegExp(r'[\d.]').hasMatch(formatted[i])) {
digitsCount++;
}
newCursor = i + 1;
}
return TextEditingValue(
text: formatted,
selection: TextSelection.collapsed(
offset: newCursor.clamp(0, formatted.length),
),
);
}