I been trying to understand how Riverpod works and was wondering how does it know when to destroy the state of a provider with the .autoDispose modifier when changing a route in Flutter. Is it somehow subscribed to the navigator changes?
The docs state:
A common use case is to destroy the state of a provider when it is no-longer used.
There are multiple reasons for doing so, such as:
- When using Firebase, to close the connection and avoid unnecessary cost.
- ***To reset the state when the user leaves a screen and re-enters it.****
CodePudding user response:
The "autoDispose" logic doesn't depend on Flutter-specific logic.
Instead it relies purely on whether a provider is currently being listened or not.
When a route is poped, the associated widgets are destroyed. This causes the ConsumerWidget
s in that route to stop listening to their "watched" providers.
Then, if a provider now has no more listener, it gets disposed.