addText method
Implementation
void addText(String text, BuildContext context) {
final currentText = _controller.text;
final currentSelection = _controller.selection;
// 验证 TextSelection 的有效性,如果无效则使用默认值
int start = currentSelection.start;
int end = currentSelection.end;
// 如果 start 或 end 为 -1,说明选择无效,使用文本长度作为默认位置
if (start == -1 || end == -1) {
start = currentText.length;
end = currentText.length;
}
// 确保 start 和 end 在有效范围内
start = start.clamp(0, currentText.length);
end = end.clamp(0, currentText.length);
// 在当前光标位置或者选区插入文本
final newText = currentText.replaceRange(
start,
end,
text,
);
// 计算新的光标位置
final newOffset = start + text.length;
// 使用 copyWith 更新 controller 的 value
_controller.value = _controller.value.copyWith(
text: newText,
selection: TextSelection.collapsed(offset: newOffset),
);
onTextChanged(_controller.text, context); // 触发 onChanged 回调
notifyListeners();
}