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,
) {
  final oldNumDecs = _numDecorators(oldValue.text);
  final newNumDecs = _numDecorators(newValue.text);

  if (!oldValue.selection.isCollapsed) {
    // if we first selected a region.
    // Don't bother and just do a clean cycle.
    return _default(oldValue, newValue);
  }

  if (newValue.text.length == oldValue.text.length - 1) {
    // Removed a single character.
    // An extra check for input prettiness.
    // For instance, when pressing `delete` on web version
    if (newNumDecs == newValue.text.length) {
      // If only decorators are left, just accept the input for ux purposes.
      _info = const CurrentMaskInfo(clean: '', isValid: false);
      return newValue;
    } else {
      return _default(oldValue, newValue);
    }
  }

  if (oldValue.text.length - oldNumDecs ==
      newValue.text.length - newNumDecs) {
    //added or deleted a decorator
    if (newValue.text.length == oldValue.text.length + 1) {
      return _addedDecorator(
        oldValue,
        newValue,
      );
    } else if (newValue.text.length == oldValue.text.length - 1) {
      return _removedDecorator(
        oldValue,
        newValue,
      );
    }
  }

  return _default(oldValue, newValue);
}