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 isInsertedCharacter =
      oldValue.text.length + 1 == newValue.text.length &&
          newValue.text.startsWith(oldValue.text);
  final isRemovedCharacter =
      oldValue.text.length - 1 == newValue.text.length &&
          oldValue.text.startsWith(newValue.text);

  if (!isInsertedCharacter && !isRemovedCharacter) {
    return oldValue;
  }

  final isNegative = newValue.text.startsWith('-');
  var newText = newValue.text.replaceAll(RegExp('[^0-9]'), '');

  // If the user wants to remove a digit, but the last character of the
  // formatted text is not a digit (for example, "1,00 €"), we need to remove
  // the digit manually.
  if (isRemovedCharacter && !_lastCharacterIsDigit(oldValue.text)) {
    final length = newText.length - 1;
    newText = newText.substring(0, length > 0 ? length : 0);
  }

  _formatter(newText, isNegative);

  if (newText.trim() == '') {
    return newValue.copyWith(
      text: isNegative ? '-' : '',
      selection: TextSelection.collapsed(offset: isNegative ? 1 : 0),
    );
  } else if (newText == '00' || newText == '000') {
    return TextEditingValue(
      text: isNegative ? '-' : '',
      selection: TextSelection.collapsed(offset: isNegative ? 1 : 0),
    );
  }

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