GardenMobile & interfaces

Inserting text at a Flutter cursor position

A small historical TextEditingController update and the selection cases it does not cover.

The original helper inserted a string at the selection’s base offset and moved the cursor after the inserted text:

// Insert text to TextField
  void insertText(String insert, TextEditingController controller) {
    final int cursorPos = controller.selection.base.offset;
    controller.value = controller.value.copyWith(
        text: controller.text.replaceRange(max(cursorPos, 0), max(cursorPos, 0), insert),
        selection: TextSelection.fromPosition(TextPosition(offset: max(cursorPos, 0) + insert.length))
    );
  }

Clamping a negative offset to zero handles one invalid-selection case. It does not bound an offset beyond the text length, replace a selected range, or manage an input method’s composing range. The max function also needs its surrounding import.

This is a narrow historical insertion example, not a complete text-editing policy. It was not run for this revision.

← Back to the garden