Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use dispose() method in dart code?

Tags:

flutter

dart

Why are we using dispose() method? I'm little confused about it. what will be issue occurs If we don't use it and what's the benefit of using it?

@override   void dispose() {     // TODO: implement dispose     super.dispose();   } 
like image 785
Shruti Ramnandan Sharma Avatar asked Jan 02 '20 05:01

Shruti Ramnandan Sharma


People also ask

What does dispose method do with?

The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

Do I need to dispose TextEditingController?

Remember to dispose of the TextEditingController when it is no longer needed. This will ensure we discard any resources used by the object. This example creates a TextField with a TextEditingController whose change listener forces the entered text to be lower case and keeps the cursor at the end of the input.

How do you dispose of a widget?

The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.


2 Answers

dispose method used to release the memory allocated to variables when state object is removed.

For example, if you are using a stream in your application then you have to release memory allocated to the stream controller. Otherwise, your app may get a warning from the PlayStore and AppStore about memory leakage.

like image 65
Viren V Varasadiya Avatar answered Sep 27 '22 20:09

Viren V Varasadiya


dispose() method called automatically from stateful if not defined.

In some cases dispose is required for example in CameraPreview, Timer etc.. you have to close the stream.

When closing the stream is required you have to use it in dispose method.

dispose() is used to execute code when the screen is disposed. Equal to onDestroy() of Android.

Example:

@override void dispose() {   cameraController?.dispose();   timer.cancel();   super.dispose(); } 
like image 24
Parth Patel Avatar answered Sep 27 '22 21:09

Parth Patel