delete method Null safety

void delete(
  1. SelectionChangedCause cause
)

Deletes backwards from the selection in textSelectionDelegate.

This method operates on the text/selection contained in textSelectionDelegate, and does not depend on selection.

If the selection is collapsed, deletes a single character before the cursor.

If the selection is not collapsed, deletes the selection.

The given SelectionChangedCause indicates the cause of this change and will be passed to onSelectionChanged.

See also:

Implementation

void delete(SelectionChangedCause cause) {
  // `delete` does not depend on the text layout, and the boundary analysis is
  // done using the `previousCharacter` method instead of ICU, we can keep
  // deleting without having to layout the text. For this reason, we can
  // directly delete the character before the caret in the controller.
  //
  // TODO(LongCatIsLooong): remove this method from RenderEditable.
  // https://github.com/flutter/flutter/issues/80226.
  final TextEditingValue controllerValue = textSelectionDelegate.textEditingValue;
  final TextSelection selection = controllerValue.selection;

  if (!selection.isValid || readOnly || _deleteNonEmptySelection(cause)) {
    return;
  }

  assert(selection.isCollapsed);
  final String textBefore = selection.textBefore(controllerValue.text);
  if (textBefore.isEmpty) {
    return;
  }

  final String textAfter = selection.textAfter(controllerValue.text);

  final int characterBoundary = previousCharacter(textBefore.length, textBefore);
  final TextSelection newSelection = TextSelection.collapsed(offset: characterBoundary);
  final TextRange composing = controllerValue.composing;
  assert(textBefore.length >= characterBoundary);
  final TextRange newComposingRange = !composing.isValid || composing.isCollapsed
    ? TextRange.empty
    : TextRange(
      start: composing.start - (composing.start - characterBoundary).clamp(0, textBefore.length - characterBoundary),
      end: composing.end - (composing.end - characterBoundary).clamp(0, textBefore.length - characterBoundary),
    );

  _setTextEditingValue(
    TextEditingValue(
      text: textBefore.substring(0, characterBoundary) + textAfter,
      selection: newSelection,
      composing: newComposingRange,
    ),
    cause,
  );
}