What does the dispose() function actually do under the hood in flutter

When we use some controllers in our widgets, I see it that we just make instances, fine
But when we call as an example:


what actually the flutter engine exactly do for that constructor

>Solution :

According to the official source here, the dispose method is a general API that is used commonly by all ChangeNotifier classes such as TextEditingController, FocusNode, etc

Discards any resources used by the object. After this is called, the
object is not in a usable state and should be discarded (calls to
addListener will throw after the object is disposed).

This method should only be called by the object’s owner.

In short, it’s "required" to prevent unwanted possibility of memory leaks (memory leaks cause that boost in RAM usage of the app).

The implementation code itself cleared up all Listeners attached to it, and it also works as a trigger to help cleanup unused resources, turning off continuous working entities such as Timers, releasing Animation related resources, when the parent object is not used anymore.

There are many use cases of what happened beneath, just look up into the open source codebase of Flutter itself. For example, try to lookup TextEditingController‘s implementation of dispose method

Yes, this is quite an abstract concept to explain, but releasing unused resources will improve your app’s performance, although not directly visible.

Leave a Reply