How to clear all SharedPreferences keys except 2 Keys in flutter

Viewed 4877

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.

2 Answers

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.

Related