replaceSelectionWithTextAndUpstreamAttributions method

void replaceSelectionWithTextAndUpstreamAttributions({
  1. required String replacementText,
  2. TextRange? newComposingRegion,
})

Replaces the currently selected text with replacementText and collapses the selection at the end of replacementText.

To insert text after a caret (collapsed selection), use insertAtCaret.

Implementation

void replaceSelectionWithTextAndUpstreamAttributions({
  required String replacementText,
  TextRange? newComposingRegion,
}) {
  if (selection.isCollapsed) {
    return;
  }

  final upstreamAttributions = _text.getAllAttributionsAt(max(selection.extentOffset - 1, 0));

  var updatedText = _text.removeRegion(
    startOffset: selection.baseOffset,
    endOffset: selection.extentOffset,
  );
  updatedText = updatedText.insertString(
    textToInsert: replacementText,
    startOffset: selection.baseOffset,
    applyAttributions: upstreamAttributions,
  );
  final updatedSelection = TextSelection.collapsed(
    offset: selection.baseOffset + replacementText.length,
  );

  update(
    text: updatedText,
    selection: updatedSelection,
    composingRegion: newComposingRegion,
  );
}