I am currently making a simple POS app. As I was writing the code for adding a new item to the menu. I thought about the potential number of listeners that would be present on the page. I decided to go with multiple, individual TextFormField
since the user can decide how many additional toppings they want to offer; each additional topping will have their own TextFomField
to enter the relevant data. Sample Structure of the TextFormField (written inside of initState())
Each TextFormField saves its value to a variable on every focus change. My worry is that if they decide to add 5 toppings then I would have 5 active listeners. So, I would like to know what is a good limit to the number of listeners I should have and is there a better solution to my problem (instead of using focus changes).
You don't have to worry about a a couple of listeners. 5 is not a relevant number by any means. If you add listeners, make sure you dispose of them when the widget is removed. Make sure to have this in your Widget for each FocusNode / Controller that has listeners.
@override
void dispose() {
// Clean up the controller when the widget is removed from the
// widget tree.
_nameFocusNode.dispose();
super.dispose();
}
Another way is to use the onChanged
property.
You could use it like this
TextFormField(onChanged: _updateName);