When we use some controllers in our widgets, I see it that we just make instances, fine But when we call as an example:
controller.dispose()
what actually the flutter engine exactly do for that constructor
CodePudding user response:
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 Timer
s, 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 ofdispose
method
Yes, this is quite an abstract concept to explain, but releasing unused resources will improve your app's performance, although not directly visible.
CodePudding user response:
Dispose is a method triggered whenever the created object from the stateful
widget is removed permanently from the widget tree. It is generally overridden and called only when the state object is destroyed. Dispose releases the memory allocated to the existing variables of the state.