I am trying to map a TextFormField
s 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
Keep
_formKey
as a state variable.By keeping as a function variable, this creates the
Form
with new instance, so your state won’t be persisted aftersetState
.Use
TextEditingController
to handle inputs ofTextFormField
instead of usingonChange
.