1

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.

Hasen
  • 11,710
  • 23
  • 77
  • 135

2 Answers2

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,
        ),
      ),
Hasen
  • 11,710
  • 23
  • 77
  • 135
-1

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

  • You have to write the code out for an answer. Otherwise this should be a comment. You can just copy and paste my code and edit what's necessary. Hint is a passed argument for the Hint Text at the moment. – Hasen Aug 04 '19 at 16:35