Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter shared_preferences not persistent?

I have been using shared_preferences in flutter, was working fine until now. Suddenly it stopped working, both in iOS and Android. I debugged it step by step and it stores data to pref and while app is on, data still persists, but after hot restart _preferencecache always is empty. How can I solve this? (version is 0.5.12)

When user logs in I save the user_id:

final prefs = await SharedPreferences.getInstance();
 final userData = json.encode(
  {
    'user_id': userID,
  },
 );
prefs.setString('userData', userData);

Later, when user restarts again:

final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('userData')) {
// print("no user data in shared preference");
  return false;
}

But the abpve function returns false, that's the issue, I checked the previous version of shared_preferences as well, but no solution.

like image 961
Greedy Pointer Avatar asked May 28 '26 23:05

Greedy Pointer


2 Answers

I assume that somewhere in your code, you faced this error and as a quick solution, you had added SharedPreferences.setMockInitialValues({}); in your code, which should be the reason (other than sharedPreferences.clear()).

The SharedPreferences.setMockInitialValues({}); is the thing that is preventing data to persist between sessions.

A quick getaway is to add a try-catch block to your code. Somethink like the following:

try {
      prefs.getInt(YOUR_KEY_HERE);
} catch (e) {
      SharedPreferences.setMockInitialValues({});
}

But this isn't a conventional fix to this problem, I recommend checking out this answer by Siddharth Agrawal.

like image 90
Broteen Das Avatar answered Jun 01 '26 09:06

Broteen Das


you have do it like this

final prefs = await SharedPreferences.getInstance();

final data = prefs.getString("userData");

if(data != null){

      final userData = json.dncode(userData);
}

   
like image 44
KlloShe Avatar answered Jun 01 '26 09:06

KlloShe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!