formatEditUpdate method

  1. @override
TextEditingValue formatEditUpdate(
  1. TextEditingValue oldValue,
  2. TextEditingValue newValue
)
override

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 (oldValue.text.length > newValue.text.length) {
    // Handle backspace: if the last character was a dash, remove the preceding digit
    final endOffset = newValue.selection.end;
    if (oldValue.text.length >= endOffset + 1 &&
        oldValue.text[endOffset] == '-') {
      return TextEditingValue(
        text: newValue.text.substring(0, endOffset - 1) +
            newValue.text.substring(endOffset),
        selection: TextSelection.collapsed(offset: endOffset - 1),
      );
    }
  }

  final StringBuffer newText = StringBuffer();
  var digitCount = 0;
  for (int i = 0; i < newValue.text.length; i++) {
    if (newValue.text[i] != '-') {
      newText.write(newValue.text[i]);
      digitCount++;
      if (digitCount == 3 || digitCount == 7 || digitCount == 14) {
        newText.write('-');
      }
    }
  }
  return TextEditingValue(
    text: newText.toString(),
    selection: TextSelection.collapsed(offset: newText.length),
  );
}