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 new value contains changes made formatter only
  if (newValue == _previousNewValue) {
    return oldValue;
  }
  _previousNewValue = newValue;

  var value = formatValue(oldValue, newValue);
  var selectionIndex = value.selection.end;

  /// format original string (adding some separators)
  final result = formatPattern(value.text);

  /// calculate count of inserted characters and count of user input characters
  var insertedSeparatorsCount = 0;
  var insertedByUserCount = 0;
  for (int i = 0; i < result.length && insertedByUserCount < selectionIndex; i++) {
    final character = result[i];
    if (isUserInput(character)) {
      insertedByUserCount++;
    } else {
      insertedSeparatorsCount++;
    }
  }

  /// adjust selection according to number of inserted characters staying before selection
  selectionIndex = min(selectionIndex + insertedSeparatorsCount, result.length);

  /// if selection is right after an inserted separator, it should be moved backward,
  /// user cannot delete separators when cursor stands right after
  if (selectionIndex - 1 >= 0 && selectionIndex - 1 < result.length &&
      !isUserInput(result[selectionIndex - 1])) {
    selectionIndex--;
  }

  return value.copyWith(
      text: result,
      selection: TextSelection.collapsed(offset: selectionIndex),
      composing: defaultTargetPlatform == TargetPlatform.iOS ? TextRange(start: 0, end: 0) : TextRange.empty);
}