Search code examples
flutterdartbloc

super.dispose() before or after controller.dispose()?


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


Solution

  • 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.

    super.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() {
      controller.dispose();
      super.dispose();
    }