Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure dispose() will be called before new widget's initState()?

Tags:

flutter

I want to use a couple of functions every time the widget is created and disposed of. But after I navigate to the next page (another widget) I expect the previous widget's dispose() should be called first. And after that, the next widget's initState() is called. But it is not working like that. I navigate to the next page and that page's initState() is called. After that previous widget's dispose() is being called.

How can I ensure that the previous widget's dispose() called first before the next widget's initState()? Or how can I achieve the same behavior without dispose()?

like image 331
Ferda Nahit FIDANCI Avatar asked Oct 22 '25 00:10

Ferda Nahit FIDANCI


1 Answers

When you are navigating to from widget A to B the first will only completely dispose() and deactivate() after the transition completes. That means that in between, both A and B are being rendered, hence, the first didn't dispose yet and the second has already inited — which makes sense, otherwise you wouldn't be able to see both at the same time when transitioning.

Because of that, you should ensure that the logic from your widget B doesn't rely on disposing widget A and decouple the dependencies between them.

Maybe by providing your use case I can update my answer with a better approach for what you need.

like image 135
Miguel Ruivo Avatar answered Oct 26 '25 19:10

Miguel Ruivo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!