'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.
Solution 1:[1]
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.
Solution 2:[2]
You can check this solution. As mentioned, you need to call the SharedPreference instance in initState.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | nivla360 |
Solution 2 | Akif |