7

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.

Sascha Derungs
  • 141
  • 1
  • 1
  • 5
  • You may want to see this: https://stackoverflow.com/questions/69960102/clear-all-cache-data-listener-state-of-provider-using-flutter-riverpod – Sangam Jan 05 '22 at 13:24

3 Answers3

8

2022

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.

Code on the Rocks
  • 11,488
  • 3
  • 53
  • 61
7

For reference, my question was answered by the owner of the Riverpod package here: https://github.com/rrousselGit/river_pod/issues/676

Sascha Derungs
  • 141
  • 1
  • 1
  • 5
1

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/

Tolga Kartal
  • 617
  • 4
  • 12
  • 14
    Hi, I’m aware of auto dispose, but my use case is different. I don’t want to use auto dispose for some of the providers while a user is logged in. But when that user logs out, I somehow need to find a way to dispose all providers, so that when I login on the same device with a different user, the state is reset. Makes sense? – Sascha Derungs Aug 07 '21 at 08:25
  • 2
    @SaschaDerungs I have the exact same issue. Did you solve this? I can't seem to find a way to clear all providers on signout. – Majoren May 09 '22 at 11:48
  • I solve the problem by setting the provider to the screen that comes after login, so when you click logout and you will remove all routes (that will dispose your provider) and navigate to the login page – Abdullah Alamodi Jan 12 '23 at 11:00