简体   繁体   English

颤振 - 如何清除焦点上的文本字段

[英]Flutter - How to clear text field on focus

How can I remove all text from a TextFormField on focus? 如何从焦点上的TextFormField删除所有文本? This was very easy in JavaScript: onfocus="this.value=''"; 这在JavaScript中非常简单: onfocus="this.value=''"; . I don't want to use a button like this: 我不想使用这样的按钮:

FlatButton(onPressed: () => _textFieldcontroller.clear(), ...)

You can use FocusNode in combination with a StatefulWidget . 您可以将FocusNodeStatefulWidget结合使用。

We keep an object of FocusNode in our class: 我们在课堂上保留了FocusNode的对象:

FocusNode _focusNode;

In the constructor of our TextFormField , we will have to pass _focusNode as a parameter: TextFormField的构造函数中,我们必须将_focusNode作为参数传递:

TextFormField(focusNode: _focusNode, ...

Now we can add a listener to our FocusNode that will always get called when the focus of our TextFormField updates. 现在我们可以向FocusNode添加一个侦听FocusNode ,当TextFormField的焦点更新时,它将始终被调用。 In it, we can check whether our FocusNode has focus or not and take action according to that. 在其中,我们可以检查我们的FocusNode是否有焦点并根据它采取行动。

_focusNode.addListener(() {
  if (_focusNode.hasFocus) _textFieldController.clear();
});

In a widget: 在小部件中:

class ExampleWidget extends StatefulWidget {
  @override
  _ExampleWidgetState createState() => _ExampleWidgetState();
}

class _ExampleWidgetState extends State<ExampleWidget> {
  FocusNode _focusNode;
  TextEditingController _textFieldController;

  @override
  void initState() {
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) _textFieldController.clear();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) => TextFormField(focusNode: _focusNode, controller: _textFieldController, ...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM