0

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?

Shobi
  • 10,374
  • 6
  • 46
  • 82

2 Answers2

2

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.

Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17
0

Use TextEditingController to handle inputs of TextFormField instead of using onChange.

Razer
  • 41
  • 2