7

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.

Greedy Pointer
  • 323
  • 5
  • 11
  • This plugin uses native shared preferences in the background (For android) and User Defaults (iOS). Haven't faced such issue yet. Which version of android are you running your app on? 10? – Jaswant Singh Oct 12 '20 at 14:30
  • You might have to show us more code. I have been using SharedPreferences since the it's been available and have never had this issue, nor have I seen anyone report anything similar. – João Soares Oct 12 '20 at 14:33
  • The above code is the main part where I use sharedpreferences, After getting data, I write it into prefs and while app is running, I can easily see it there but later after a restart, no data is there. What should I show more, maybe you can specify, so I add.. – Greedy Pointer Oct 12 '20 at 14:40
  • Yes 10, but I tried in 9 in emulator as well the same result unfortunately:( – Greedy Pointer Oct 12 '20 at 14:41

2 Answers2

0

I realized I was clearing my shared preferences some where in my app and I had forgotten about it. Please check every where in your code for sharedPreferences.clear(). You never know.

nivla360
  • 793
  • 11
  • 20
-1

You can check this solution. As mentioned, you need to call the SharedPreference instance in initState.

Akif
  • 6,084
  • 7
  • 20
  • 47