5

How can I clear the current state of my 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.

John
  • 2,551
  • 3
  • 17
  • 29

2 Answers2

5

You can use keys to hard-reset the state of a subtree.

And if you want to reset the subtree only partially, you can add a GlobalKey on the top of the other key.

In the end you'll have:

Widget build(BuildContext context) {
  return Provider(
    key: ObjectKey(someIdentifier),
    builder: (_) => Foo(),
    child: SomeSubtree(
      key: GlobalObjectKey(context),
    ),
  );
}

In such case, if someIdentifier changes, the state of Provider will reset but Subtree will be preserved.

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • Where do you suggest storing the value of 'someIdentifier' to ensure the state isn't hard-reset unintentionally? – John Sep 03 '19 at 19:34
  • That depends on your use-case. It could be the userID for example – which doesn't need to be stored anywhere – Rémi Rousselet Sep 03 '19 at 19:41
0

The solution for me was to reset the values in the init state. Code: https://stackoverflow.com/a/73732182/16684431.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 20 '22 at 11:36