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.
simply use clear() function with your variable it will clear all the shared preferences. SharedPreferences preferences = await SharedPreferences. getInstance(); await preferences. clear();
Let start on Project make a flutter project and add dependence and after that, you can clear your main dart file source code. In your main. dart file we create a login page UI and here can entry the user details and on button click store the data in share preferences. so follow full source code on these main.
SharedPreferences prefs = await SharedPreferences. getInstance(); bool boolValue = prefs. getBool('option'); Important: You can only save int, String, double or bool variables using SharedPreferences.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With