Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is TextEditingController always used in Stateful widgets?

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?

like image 260
albaniantech Avatar asked Jan 25 '23 10:01

albaniantech


1 Answers

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 = ..;
}
like image 144
creativecreatorormaybenot Avatar answered Feb 02 '23 20:02

creativecreatorormaybenot