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,
) {
  var valueText = newValue.text;

  if (valueText.isEmpty) {
    return newValue;
  }

  valueText = _sanitizeDecimalSeparatorIfNeeded(valueText);

  if (allowDecimals && valueText == _defaultDecimalSeparator) {
    return allowDecimals ? _prefixedDecimalSeprator : oldValue;
  }

  if (!_isNumber(valueText)) {
    return oldValue;
  }

  final periods = _periodRegExp.allMatches(valueText);

  if (periods.length > 1) {
    return oldValue;
  }

  if (_isStringTooLong(valueText)) {
    return oldValue;
  }

  num? number;

  try {
    number = _defaultNumberFormatter.parse(valueText);
    // ignore: empty_catches
  } catch (e) {}

  if (number != null) {
    if (number > maxValue) {
      return oldValue;
    }

    final text = _formatNumberToString(number, valueText, periods.isNotEmpty);
    final position = TextPosition(offset: text.length);
    final selection = TextSelection.fromPosition(position);

    return TextEditingValue(text: text, selection: selection);
  }

  return oldValue;
}