skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Use TextEditingController to handle inputs of TextFormField instead of using onChange.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search