flutterdartsharedpreferences

How to clear all SharedPreferences keys except 2 Keys in flutter


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.


Solution

  • 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);
              }
            }