insertAtCaret method

void insertAtCaret({
  1. required String text,
  2. TextRange? newComposingRegion,
})

Inserts the given text at the current caret position.

The current composingAttributions are applied to the given text and the caret is moved to the end of the given text.

If the current selection is expanded, this method does nothing, because there is no conceptual caret with an expanded selection.

Implementation

void insertAtCaret({
  required String text,
  TextRange? newComposingRegion,
}) {
  if (!selection.isCollapsed) {
    textFieldLog.warning('Attempted to insert text at the caret with an expanded selection. Selection: $selection');
  }

  final updatedText = _text.insertString(
    textToInsert: text,
    startOffset: selection.extentOffset,
    applyAttributions: Set.from(composingAttributions),
  );

  final updatedSelection = _moveSelectionForInsertion(
    selection: selection,
    insertIndex: selection.extentOffset,
    newTextLength: text.length,
  );

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