Reputation: 171
How can I clear the current state of my Riverpod providers manually in my Flutter app? The use case I have is when a user signs out of my app then signs up as a new/different user the previous users state is still stored in the providers, it is cleared automatically when the app is restarted however.
Upvotes: 10
Views: 17955
Reputation: 21
If you are using the same ProviderContainer
for all your providers. An easy way around it would be to call
void logout() {
var providers = ref.container.getAllProviderElements();
for (var element in providers) {
element.invalidateSelf();
}
}
Upvotes: 0
Reputation: 17576
There is now an invalidate() method that causes the provider to be disposed immediately.
Example usage:
onPressed: () async {
ref.read(newPostScreenProvider.notifier).setBusy(true);
await ref.read(newPostScreenProvider.notifier).submitPost(
image: ref.watch(imagesProvider),
content: ref.watch(contentProvider),
private: private,
);
ref.read(newPostScreenProvider.notifier).setBusy(false);
ref.invalidate(newPostScreenProvider);
ref.invalidate(imagesProvider);
ref.invalidate(contentProvider);
ref.invalidate(contentReadyProvider);
router.pop();
}
Here's a GitHub issue describing the invalidate method.
Upvotes: 15
Reputation: 171
For reference, my question was answered by the owner of the Riverpod package here: https://github.com/rrousselGit/river_pod/issues/676
Upvotes: 7
Reputation: 633
You will need to use .autoDispose from Riverpod, see below link for more details
final userProvider = StreamProvider.autoDispose<YourModel>((ref) {
});
https://riverpod.dev/docs/concepts/modifiers/auto_dispose/
Upvotes: 2