颤振如何使用TextField中的当前值更新提示文本 [英] Flutter how to update hint text with current value in TextField

查看:100
本文介绍了颤振如何使用TextField中的当前值更新提示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个文本字段,因此当我单击它时,它将清除该值-否则,您必须先删除当前值,然后才能键入一个新值。问题是,当我单击时,可以看到原始的提示文本,因为它看起来像已被重置,所以可能会造成混乱。

I have a Textfield set up so when I click on it it clears the value -otherwise you have to delete the current value before you can type a new one. The problem is, when I click, the original hint text can be seen which can be quite confusing since it looks like it's been reset.


因此,例如,原始提示文本在文本字段中显示 25 ,然后输入新值 48 。但是,如果我再次单击以再次输入新值,则原来的 25 提示文本值在焦点消失后会再次显示。

So for example, the original hint text shows 25 in the text field, then I input a new value of 48. But if I click again to input a new value once more, the original 25 hint text value is displayed again after it clears on focus.



  final TextEditingController control;
  final Function onchanged;
  FocusNode _focusNode;

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

  TextField(
        focusNode: _focusNode,
        controller: control,
        onChanged: onchanged,
        decoration: InputDecoration(
          hintText: hint,
        ),
      ),

我该怎么做它是否使提示文本更新为先前的值(在清除之前),以便在单击时显示相同的值?

How can I make it so the hint text updates to the previous value (before it is cleared) so that when clicked it shows the same value? This is normal behaviour in form fields so I would like to achieve this.

推荐答案

为清楚起见,答案是设置值分配给 hintText hint 字符串中的值,紧接在控制器文本值的最后一个值之前已清除。这是在 FocusNode 侦听器中使用 setState 完成的。

For clarity, the answer is to set the value of the hint string which is assigned to hintText, to the last value of the controller's text value, right before it is cleared. This is done in the FocusNode listener using setState.

  String _hint;
  final TextEditingController control;
  final Function onchanged;
  FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        setState(() {
          _hint = control.text;
        });
        control.clear();
      }
    });
  }

  TextField(
        focusNode: _focusNode,
        controller: control,
        onChanged: onchanged,
        decoration: InputDecoration(
          hintText: _hint,
        ),
      ),

这篇关于颤振如何使用TextField中的当前值更新提示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆