Home > Software design >  super.dispose() before or after controller.dispose()?
super.dispose() before or after controller.dispose()?

Time:07-09

I'm working with PageController and after the last page I want to change view, so I should dispose the controller. If I call controller.dispose() before super.dispose() I get this error:

_IntroViewState failed to call super.dispose()

If I call controller.dispose() after super.dispose() no exception is thrown. Which is the correct way? The code is here: https://pastebin.com/PK1SWnsm

CodePudding user response:

You should always call super.initState() before anything at the start and super.dispose() after doing something at the end.

CodePudding user response:

A dispose method is a callback we use when we want to end something's use.

If we create a stream in our initState method, we need to dispose of it in the dispose function as soon as we are done. If we don't, we will use up unnecessary resources such as memory and storage that we don't need, since we are not using that stream. We may have memory leaks in our application, and it can affect the user experience negatively.

suepr.dispose() disposes of the parent class, which is the public class IntroView. The controller is one object within the class. Therefore, before disposing the widget, we need to dispose anything in the widget.

So to answer your question, do controller.dispose(), and then super.dispose().

@override
void dispose() {
  super.dispose();
  controller.dispose();
}

CodePudding user response:

The official documentation answers that:

Implementations of this method should end with a call to the inherited method, as in super.dispose().

Translating to code, the correct is:

    @override
    void dispose() {
        doWhateverYouNeedToDo();
        myController.dispose()

        // in the last line of the method:
        super.dispose()
    }

Reference:

Edit:

About the error in your code, it is probably caused by how you used Bloc, and it is not related to the Widget disposal of itself.

I changed the code you provided to remove the Bloc and the dispose work as expected when super.dispose() is called at the end:

https://dartpad.dev/?id=6a3f3567f880997219fa21ac9736ea46

To help you better, we need a full-working example that shows the error happening when super.dispose() is called at the end.

  • Related