I'm trying to clear all the key values of SharedPreferences during logout except 2 keys "EmailID"
and "Password"
. As we know that there is only single SharedPreferences instance allowed in flutter so I can't make a different instance for storing "EmailID"
and "Password"
and remove a particular key is not a good practice to remove 20+ keys. If i used prefs.clear();
that will clear all the key values any help much-appreciated thanks.
How to clear all SharedPreferences keys except 2 Keys in flutter
Asked Answered
just for anxiety, why you want to keep email and password after logout? It should get cleared as well. –
Lasonyalasorella
if user check the remember password so i stored a Boolean flag, only in that case i need to keep store email and password that will help to login again without type email and password –
Haemolysin
You could clear the sharedpreferences and rewrite EmailID and Password (that you saved in a variable before clearing) –
Arboreal
There is no way to avoid this, You have to clear those value one by one.
You have to iterate shared preferences keys and avoid keys which you don't want to clear.
SharedPreferences preferences = await SharedPreferences.getInstance();
for(String key in preferences.getKeys()) {
if(key != "email" && key!= "password") {
preferences.remove(key);
}
}
An alternative and simple way is as follows:
String _email = prefs.email;
String _password = prefs.password;
prefs.clear();
prefs.email = _email;
prefs.password = _password;
Depending on how much information you have in SharedPreferences, this is probably a more efficient function than iterating each key
P.S. Storing a password in SharedPreferences is not recommended.
Create a List to hold the keys you want to keep
final List<String> keysToKeep = ['Password', 'EmailID',]
Then get all stored keys from shared preferences
final Set<String>? allKeys = preferences?.getKeys();
You can use difference method to exclude those keys from all keys
https://api.flutter.dev/flutter/dart-core/Set/difference.html
final Set<String> keysToRemove = allKeys.difference(keysToKeep.toSet());
for (final key in keysToRemove) {
log('Removing key: $key');
preferences!.remove(key);
}
© 2022 - 2025 — McMap. All rights reserved.