deleteText method

void deleteText(
  1. BuildContext context
)

Implementation

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

  final text = _controller.text;
  final selection = _controller.selection;

  // 验证 TextSelection 的有效性
  int offset = selection.baseOffset;
  if (offset == -1) {
    offset = text.length;
  }

  offset = offset > 0 ? offset : text.length;
  if (offset <= 0) return;

  bool isEmoji = _containsEmoji(text);

  int deleteLength = isEmoji ? 2 : 1;
  if (offset - deleteLength < 0) {
    deleteLength = 1;
  }

  final newText =
      text.substring(0, offset - deleteLength) + text.substring(offset);
  _controller.text = newText;
  _controller.selection =
      TextSelection.collapsed(offset: offset - deleteLength);
  onTextChanged(_controller.text, context); // 触发 onChanged 回调
  notifyListeners();
}