如何检测何时在 Flutter 中选择了 TextField? [英] How to detect when a TextField is selected in Flutter?
问题描述
我有一个 Flutter TextField,当该字段被选中时,它会被软键盘覆盖.显示键盘时,我需要向上滚动字段并移开.这是一个非常常见的问题,StackOverflow 中提供了解决方案发帖.
I have a Flutter TextField which gets covered by the soft keyboard when the field is selected. I need to scroll the field up and out of the way when the keyboard is displayed. This is a pretty common problem and a solution is presented in this StackOverflow post.
我想我已经弄清楚了 ScrollController 部分,但是如何检测何时选择了 TextField?似乎没有任何事件方法(例如 onFocus()、onSelected()、onTap() 等).
I think I have the ScrollController part figured out but how do I detect when the TextField has been selected? There doesn't appear to be any event method (e.g. onFocus(), onSelected(), onTap(), etc).
我尝试将 TextField 包装在 GestureDetector 中,但这也不起作用 - 显然该事件从未被捕获.
I tried wrapping the TextField in a GestureDetector but that didn't work either -- apparently the event was never captured.
new GestureDetector(
child: new TextField(
decoration: const InputDecoration(labelText: 'City'),
),
onTap: () => print('Text Selected'),
),
这是一个基本要求,我知道必须有一个简单的解决方案.
This is such a basic requirement that I know there must be an easy solution.
推荐答案
我想你正在寻找 FocusNode
.
I suppose you are looking for FocusNode
.
要监听焦点变化,您可以在 FocusNode
中添加一个监听器,并将 focusNode
指定到 TextField
.
To listen to focus change, you can add a listner to the FocusNode
and specify the focusNode
to TextField
.
例子:
class TextFieldFocus extends StatefulWidget {
@override
_TextFieldFocusState createState() => _TextFieldFocusState();
}
class _TextFieldFocusState extends State<TextFieldFocus> {
FocusNode _focus = FocusNode();
TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_focus.addListener(_onFocusChange);
}
@override
void dispose() {
super.dispose();
_focus.removeListener(_onFocusChange);
_focus.dispose();
}
void _onFocusChange() {
debugPrint("Focus: ${_focus.hasFocus.toString()}");
}
@override
Widget build(BuildContext context) {
return new Container(
color: Colors.white,
child: new TextField(
focusNode: _focus,
),
);
}
}
这个要点表示如何确保焦点节点在 ui 上可见.
This gist represents how to ensure a focused node to be visible on the ui.
希望对你有帮助!
这篇关于如何检测何时在 Flutter 中选择了 TextField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!