replaced method Null safety

TextEditingValue replaced(
  1. TextRange replacementRange,
  2. String replacementString
)

Returns a new TextEditingValue, which is this TextEditingValue with its text partially replaced by the replacementString.

The replacementRange parameter specifies the range of the TextEditingValue.text that needs to be replaced.

The replacementString parameter specifies the string to replace the given range of text with.

This method also adjusts the selection range and the composing range of the resulting TextEditingValue, such that they point to the same substrings as the corresponding ranges in the original TextEditingValue. For example, if the original TextEditingValue is "Hello world" with the word "world" selected, replacing "Hello" with a different string using this method will not change the selected word.

This method does nothing if the given replacementRange is not TextRange.isValid.

Implementation

TextEditingValue replaced(TextRange replacementRange, String replacementString) {
  if (!replacementRange.isValid) {
    return this;
  }
  final String newText = text.replaceRange(replacementRange.start, replacementRange.end, replacementString);

  if (replacementRange.end - replacementRange.start == replacementString.length) {
    return copyWith(text: newText);
  }

  int adjustIndex(int originalIndex) {
    // The length added by adding the replacementString.
    final int replacedLength = originalIndex <= replacementRange.start && originalIndex < replacementRange.end ? 0 : replacementString.length;
    // The length removed by removing the replacementRange.
    final int removedLength = originalIndex.clamp(replacementRange.start, replacementRange.end) - replacementRange.start; // ignore_clamp_double_lint
    return originalIndex + replacedLength - removedLength;
  }

  final TextSelection adjustedSelection = TextSelection(
    baseOffset: adjustIndex(selection.baseOffset),
    extentOffset: adjustIndex(selection.extentOffset),
  );
  final TextRange adjustedComposing = TextRange(
    start: adjustIndex(composing.start),
    end: adjustIndex(composing.end),
  );
  assert(_textRangeIsValid(adjustedSelection, newText));
  assert(_textRangeIsValid(adjustedComposing, newText));
  return TextEditingValue(
    text: newText,
    selection: adjustedSelection,
    composing: adjustedComposing,
  );
}