背景
使用Visibility来控制清理按钮的显示和隐藏,在设置Visibility的状态时,会导致TextField焦点丢失。使用AnimatedOpacity代替Visibility
在光标丢失后手动设置光标位置
dart
void _setFocus({int? baseOffset}) {
final int currentPosition =
baseOffset ?? textController.selection.baseOffset;
Future.delayed(Duration(milliseconds: 100), () {
// Move focus to the end of the current text
focusNode.requestFocus();
Future.delayed(Duration(milliseconds: 100), () {
// Save the current cursor position
textController.selection = TextSelection.fromPosition(
TextPosition(offset: currentPosition),
);
});
});
}