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) {
  StringBuffer newText = StringBuffer();
  String digitsOnly = newValue.text.replaceAll(RegExp(r'[^0-9/]'), '');

  // If the old value and new value are the same, the user is pressing backspace
  if (oldValue.text.length > newValue.text.length) {
    return TextEditingValue(
      text: newText.toString(),
      selection: TextSelection.collapsed(offset: newText.length),
    );
  }

  for (int i = 0; i < digitsOnly.length; i++) {
    if (i == 2 && digitsOnly.length < 5) {
      newText.write('/');
    }
    newText.write(digitsOnly[i]);
  }

  return TextEditingValue(
    text: newText.toString(),
    selection: TextSelection.collapsed(offset: newText.length),
  );
}