rrousselGit / flutter_hooks

React hooks for Flutter. Hooks are a new kind of object that manages a Widget life-cycles. They are used to increase code sharing between widgets and as a complete replacement for StatefulWidget.
MIT License
3.07k stars 175 forks source link

Custom hook calling dispose in reverse mode #318

Closed antonio-nicolau closed 1 year ago

antonio-nicolau commented 1 year ago

Custom hook is calling dispose in reverse mode

I'm using custom hook on my project to initialise and configure ChewieController and I was getting the error chewieController used after being disposed because of that I decided investigate wtf 🤬 is going on and I realised that my custom hook is calling dispose in reverse order, I mean, after put logs on initHook and dispose I saw that it calls dispose after initHook.

When does it happen ?

I have a video page which receive a videoId as param, I call my custom hook here. When I click on button to call this page again passing a different param (videoId), Flutter remove this page from widget tree and call it again with different videoId. While it happen you can see on logs dispose being called after initHook causing that if I initialise something on initHook it will be disposed and will throw an error when I try to access it later

NOTE it doesn't happen just with beamer package but even doing it with Navigator.pop and Navigator.push

To Reproduce

I created a reproduced code, you can find here

https://user-images.githubusercontent.com/67912928/180266819-19d2dff8-af40-4eb7-bc13-0a126d6eb5e2.mov

Please pay attention on logs and you'll see dispose being called after initHook

Expected behavior When close video_page and call it again should call dispose and after that initHook

rrousselGit commented 1 year ago

Your example is in fact unrelated to flutter_hooks.

It's not hooks that are disposed in reverse order. It's the pages themselves.

It's either Flutter or your navigator here that decides to dispose pages in this order. flutter_hooks only disposes of the hooks when the associated widget is disposed.

antonio-nicolau commented 1 year ago

I see 🤔 so does anyone knows how to bypass this situation ?

iamsahilsonawane commented 1 year ago

I see 🤔 so does anyone knows how to bypass this situation ?

I can see in the video attached that after all of the navigations when navigating back, you're directly going to the initial page when you go back.

In my guess, you're using directly replacing the routes for navigation and therefore the previous page is getting disposed of. And according to @rrousselGit "flutter_hooks only disposes of the hooks when the associated widget is disposed" so the hooks are disposing with it too!