deleteText method

void deleteText(
  1. BuildContext context
)

Implementation

void deleteText(BuildContext context) {
  if (_controller.text.isEmpty) return;

  final text = _controller.text;
  final currentSelection = _controller.selection;
  final selection = currentSelection.isValid
      ? TextSelection(
          baseOffset: currentSelection.baseOffset.clamp(0, text.length),
          extentOffset: currentSelection.extentOffset.clamp(0, text.length),
        )
      : TextSelection.collapsed(offset: text.length);
  final boundary = CharacterBoundary(text);

  late final int deleteStart;
  late final int deleteEnd;
  if (!selection.isCollapsed) {
    deleteStart = boundary.getLeadingTextBoundaryAt(selection.start) ?? 0;
    deleteEnd =
        boundary.getTrailingTextBoundaryAt(selection.end - 1) ?? text.length;
  } else {
    final offset = selection.extentOffset;
    if (offset == 0) return;
    deleteStart = boundary.getLeadingTextBoundaryAt(offset - 1) ?? 0;
    deleteEnd = boundary.getTrailingTextBoundaryAt(offset - 1) ?? offset;
  }

  final newText = text.replaceRange(deleteStart, deleteEnd, '');
  _controller.value = TextEditingValue(
    text: newText,
    selection: TextSelection.collapsed(offset: deleteStart),
  );
  onTextChanged(_controller.text, context); // 触发 onChanged 回调
  notifyListeners();
}