4
votes

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?

1

1 Answers

7
votes

Long answer short

You need to dispose your TextEditingController in State.dispose:

TextEditingController textEditingController;

@override
void dispose() {
  textEditingController.dispose(); // You need to do this.

  super.dispose();
}

Explanation

A TextEditingController is a ChangeNotifier as TextEditingController inherits from ValueNotifier and ValueNotifier extends ChangeNotifier.

Having said that, TextEditingControllers 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 = ..;
}