Flutter - How to wipe provider data after user signed out from app?

Viewed 2505

I am using provider for state management in my flutter application. I have implemented provider using Multiprovider.

I want to wipe provider data when the user signed out from the app I have read out this comment but don't understand it well.

3 Answers

If you rebuild your MultiProvider widget with a different key, it reset the state, hence, rebuild the providers. That's what is explained there.

Hence, what you need to do in order to achieve it, is something like:

String userId = myUserId;

void signOut() {
   setState(() => userId = '');
}

Widget build(BuildContext context) {

  return MultiProvider(
    key: ObjectKey(userId),
    providers: // Your providers
    child: SomeSubtree(),
  );
}

Assuming you are using a StatefulWidget, in this case. You can read more about how keys work in Flutter here.

The idea is to clear the state when the user wants to logOut, mainly by setting the token to null

And also if you stored these user data in the device you should clear them. For me I use sharedprefrences.

example of my code

  Future<void> logOut() async {
    _token = null;
    notifyListeners();
    final prefs = await SharedPreferences.getInstance();
    prefs.clear();
  }

if you stored other data also set it to null, and be sure to notifyListeners after setting these data to null.

I suppose that you did the multiprovder correctly, so I only get you the idea to do the LogOut

The problem is when user A logout, and then user B login, the old data of user A still here.

To fix that problem I have 3 solutions:

1/. In every ChangeNotifierProxyProvider for update prop, have to check state of login status, and return new Provider, otherwise return updated Provider

And on other Provider doesn't depend on login status, we have to manually call the function to clear data.

2/. Another solution is try to rebuild mainApp again when logout. Ex: https://stackoverflow.com/a/68572345/1122308

And it maybe does not work for some app because structure is different. If you want it work for your app, please post your app's code. We can help you.

3/. Restart OS level your app when logout by this package: https://pub.dev/packages/restart_app

It's ok but not good for UX. And iOS doesn't work https://github.com/gabrimatic/restart_app/issues/1

Related