While reading the Flutter documentation, I came across this article that shows how to handle changes to a text field. What I found interesting is that in this and all other articles regarding TextEditingController
, the TextEditingController
is always used in a Stateful widget regardless of whether that widget needs to be stateful or not.
What is the reason that TextEditingController
is always used with Stateful widgets?
You need to dispose your TextEditingController
in State.dispose
:
TextEditingController textEditingController;
@override
void dispose() {
textEditingController.dispose(); // You need to do this.
super.dispose();
}
A TextEditingController
is a ChangeNotifier
as TextEditingController
inherits from ValueNotifier
and ValueNotifier
extends ChangeNotifier
.
Having said that, TextEditingController
s need to be disposed in order to not leak any resources.
Anytime you want to dispose something, you will want to make use of the StatefulElement.unmount
. This is exposed via State
and with that StatefulWidget
. See above for how to implement this.
Ideally, you will set up your controller in initState
:
@override
void initState() {
super.initState();
textEditingController = ..;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With