Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Delete only user data on logout

On logout, don't wipe the whole local storage. It holds two kinds of data: the user's data (tokens, cached profile, favorites, last opened episode) and device settings (theme, language, "onboarding seen"). Logout should remove the first kind and keep the second. Otherwise the user logs back in and the app greets them in the wrong language with the wrong theme.

So never this:

await sharedPreferences.clear();

Instead, give each local data class one method that removes only its user keys:

class PreferencesLocalData {
  const PreferencesLocalData({
    required this.sharedPreferences,
  });

  final SharedPreferences sharedPreferences;

  // theme, language, onboarding stay untouched

  Future<void> clearUserData() async {
    await Future.wait([
      sharedPreferences.remove(_lastEpisode),
      sharedPreferences.remove(_favorites),
    ]);
  }
}

And logout calls them all:

Future<void> logout() async {
  await Future.wait([
    preferencesLocalData.clearUserData(),
    secureStorageLocalData.clearUserData(),
  ]);
}

One thing to watch: every new user key must also be added to clearUserData. If you want that to be automatic, two alternatives: keep the keys in two enums, UserDataKey and SettingsKey, and loop over the user one. Or start every user key with user_ and remove by prefix.

Kamran Bekirov
Kamran Bekirov

Want this level of care in your Flutter apps?

Work With Me