Search code examples
flutterdartfocuslost-focustextformfield

Change Value of TextFormField when leaving focus


I have a TextFormField that, if the user leaves it, should fill with specific Text. So for example, if the user edits the field and enters "Test", and I don't want to allow the String "Test", then as soon as the field looses focus it should replace the Text with "Sike!". So something like onChanged, but the event being the loss of Focus, not a change of value, which is what I had so far:

TextFormField(
   controller: myController,
   onChanged: (value) {
     if (value == "Test"){
       myController.text = "Sike!";
     }
   },
.............
.............

Solution

  • One way you can do this is like so.

    class _DemoState extends State<Demo> {
      final node = FocusNode();
      final tc = TextEditingController();
    
      @override
      void initState() {
        node.addListener(() {
          if (!node.hasFocus && tc.text == 'Test') {
            tc.text = "Sike!";
          }
        });
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return TextFormField(
          controller: tc,
          focusNode: node,
        );
      }
    }