Flutter how to update hint text with current value in TextField

耗尽温柔 提交于 2020-04-18 07:06:32

问题


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.

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.


回答1:


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,
        ),
      ),



回答2:


Before you clear the textField controller, update the hint variable using setState with the value from the controller. That should do the work.



来源:https://stackoverflow.com/questions/57348044/flutter-how-to-update-hint-text-with-current-value-in-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!