Search code examples
flutterdispose

How and Where to Call Dispose in Flutter


I was reading on how to use dispose on flutter but I cannot figure it out. If I call the below pagedispose function after Navigator.pushReplacementNamed, I am always getting an error. If I call this function from another class page, I then get errors that it doesn't exist etc.

Would appreciate your guidance on how to clear all running functions etc on a page when transitioning to another Flutter page.

@override
void pagedispose(){   
    vtimer.cancel();   
    vcontroller.dispose();   
    super.dispose();   
 }

Thanks in advance.


Solution

  • According to the documentation

    dispose method

    Called when this object is removed from the tree permanently.

    Regarding a page, the dispose method is called when the page is removed from the navigation stack. Here is a good explanation of Navigation.
    When your widget (page) extends StatefulWidget, it's not mandatory but you can override the dispose method to execute additional instructions depending on your need. The method is called automatically when the page is being removed from navigation tree. Override the method as following

    @override
    void dispose() {
      // your desired instructions here
    
      super.dispose(); // This will free the memory space allocated to the page
    }
    

    Nonetheless, the method void pagedispose() cannot be overridden as it ain't a known method of StatefulWidget