insertAtCursor method

void insertAtCursor(
  1. String textToInsert
)

Adds textToInsert to the text of the controller while also keeping the selection intact

Implementation

void insertAtCursor(String textToInsert) {
  final textBefore =
      selection.baseOffset < 1 ? "" : text.substring(0, selection.baseOffset);
  final textAfter =
      selection.baseOffset < 1 ? "" : text.substring(selection.extentOffset);
  final newText = textBefore + textToInsert + textAfter;
  final endPositionAfterInsert = textBefore.length + textToInsert.length;
  final newSelection = TextSelection(
    baseOffset: endPositionAfterInsert,
    extentOffset: endPositionAfterInsert,
  );
  value = value.copyWith(
    text: newText,
    selection: newSelection,
  );
}