Search code examples
flutterflutter-state

Can't use a setState call in the onchanged callback in flutter


I am trying to map a TextFormFields value to a state variable in flutter

class _PageState extends State<AddPage> {

  String _tag = ''; // this is the state variable

  @override
  Widget build(BuildContext context) {
    final _formKey = GlobalKey<FormState>();
       ....
      return Scaffold(
          ....
          ....
          TextFormField(
                  decoration: const InputDecoration(labelText: "Tag *"),
                  onChanged: (val) {
                      print(val);
                      setState(() {
                        _tag = val; // here I am trying to update the state variable
                      });
                  },
                ), // TextFormField end

    )};
    }
}

as you can see I am listening to the onChanged event and trying to update the state variable _tag.

but the state does not update and the text field loses focus ( I think because the UI rerendors because of the setState() call). No character is displayed the form field as well. any idea what I am doing wrong? am I listening to the right event?


Solution

  • Keep _formKey as a state variable.

    class _PageState extends State<AddPage> {
    
      String _tag = ''; // this is the state variable
      final _formKey = GlobalKey<FormState>();
    
      @override
      Widget build(BuildContext context) {
           ....
          return Scaffold(
              ....
              ....
              TextFormField(
                      decoration: const InputDecoration(labelText: "Tag *"),
                      onChanged: (val) {
                          print(val);
                          setState(() {
                            _tag = val; // here I am trying to update the state variable
                          });
                      },
                    ), // TextFormField end
    
        )};
        }
    }
    

    By keeping as a function variable, this creates the Form with new instance, so your state won't be persisted after setState.