Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 582
Sanjeev Sangral Avatar asked Jun 05 '19 07:06

Sanjeev Sangral


People also ask

How do I clear all SharedPreferences in flutter?

simply use clear() function with your variable it will clear all the shared preferences. SharedPreferences preferences = await SharedPreferences. getInstance(); await preferences. clear();

How do I keep logged in using shared preferences flutter?

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.

How do you store Boolean value in SharedPreferences in flutter?

SharedPreferences prefs = await SharedPreferences. getInstance(); bool boolValue = prefs. getBool('option'); Important: You can only save int, String, double or bool variables using SharedPreferences.


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);
          }
        }
like image 61
Jitesh Mohite Avatar answered Nov 15 '22 11:11

Jitesh Mohite


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.

like image 37
David L Avatar answered Nov 15 '22 11:11

David L