插入文本到TextField
void insertText(String text) {
final currentText = _textEditingController.text;
int cursorIndex = _textEditingController.selection.baseOffset;
if (cursorIndex == -1) cursorIndex = 0;
final beforeText = currentText.substring(0, cursorIndex);
final afterText = currentText.substring(cursorIndex, currentText.length);
cursorIndex += text.length;
final selection = TextSelection(baseOffset: cursorIndex, extentOffset: cursorIndex);
_textEditingController.value = TextEditingValue(
text: "$beforeText$text$afterText",
selection: selection,
);
}
删除文本到TextField
void deleteText() {
int getNewCursorPos(List<int> runes, int runeOffset) {
return String.fromCharCodes(runes.sublist(0, runeOffset)).length;
}
final int cursorPos = _textEditingController.selection.baseOffset;
if (cursorPos > 0) {
final String text = _textEditingController.text;
final List<int> textRunes = text.runes.toList();
final runeOffset = text.substring(0, cursorPos).runes.length;
if (runeOffset > 0) {
textRunes.removeAt(runeOffset - 1);
_textEditingController.text = String.fromCharCodes(textRunes);
_textEditingController.selection = TextSelection.fromPosition(
TextPosition(offset: getNewCursorPos(textRunes, runeOffset - 1)),
);
}
}
}