Flutter shared_preferences not persistent? - flutter

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.

you have do it like this
final prefs = await SharedPreferences.getInstance();
final data = prefs.getString("userData");
if(data != null){
final userData = json.dncode(userData);
}

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.

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.

Related

emulator always clear moor database

I am using drift as database for my flutter app.
Whenever I close the emulator tab and restart it again, then all the saved data are gone.
This is my way to open the database:
LazyDatabase connect() {
return LazyDatabase(() async {
final appDir = await getApplicationDocumentsDirectory();
final dbPath = p.join(appDir.path, 'db.sqlite');
return NativeDatabase.createInBackground(File(dbPath));
});
}
It doesn't happen on my own physical device though.
Best regards.

How to get value of variable from function?

I am trying to get value from a function and store it in a variable but I am getting null.
String imgUrl='';
getUrlSP() async {
SharedPreference preferences
=await SharedPreferences.getInstance();
String Url =
preferences.getString('imageUrl').toString();
setState(() {
imgUrl=Url;
});
print('Printing Image Url inside function:${imgUrl}');
}
outside function
print('Image Url :${imgUrl}');
The results I got in the terminal are
I/flutter (32164): Image Url :
I/flutter (32164): Image Url Stored in Prefs
is:https://firebasestorage.googleapis.com/v0/b/veeluser.appspot.com/o/User%20Images%2FdCP6WEESxfYNDIMqtt57n2BsxYf1?alt=media&token=d864a502-209f-4262-9860-b9d4d3222091
_As from the above results that I got in terminal I am not getting the value of imageUrl outside the function._As I am new to flutter so if there is an error or there is any other solution please share it.
That is expected. since your getUrlSP function is declared as async, you'll need to use await when calling it to ensure it completes (and sets imgUrl) before the rest of your code runs.
So:
await getUrlSP();
print('Image Url :${imgUrl}');
I recommend taking the Flutter codelab Asynchronous programming: futures, async, await
should be used setString() to add a string value to the shared preferences .
Example :
String imgUrl='';
getUrlSP() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('imageUrl', imgUrl);
print('==> ${imgUrl} <==');
}

How to save data in my settings menu in Flutter?

I was wondering how to save data locally in Flutter. I am creating a Settings menu in my app, and I have a draft made of that UI, but I want to save the user's preferences when they close that menu, but I have no idea how to accomplish that.
Do you know some tutorial to do so? I have searched in Youtube, but I have no idea how to search for it. I have only found UI tutorials and I don't want that.
A picture of my UI is (I want to save that boolean option).
I would appreciate any help you could give to me!
You should use shared_preferences package. It's very simple and it's for non-critical data like this! Here is an example how to use it:
class SettingsRepository {
final SharedPreferences preferences;
SettingsRepositoryImpl(this.preferences);
Future<int> getDifficulty() {
return preferences.getInt(Keys.difficulty) ?? 1;
// this 1 in the end is a default value
}
Future setDifficulty(int difficulty) {
return preferences.setInt(Keys.difficulty, difficulty);
}
}
To learn more go to https://pub.dev/packages/shared_preferences. I assume you want to call preferences.setBool
You can save your boolean option using shared preferences.
Future<Null> saveOption(bool isSelected) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('option', isSelected);
}
Then you can get the option from there.
Future<bool> getOption() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool('option');
}
You can read more from here.

Flutter SharedPreferences resetting the data

I have this code in flutter using SharedPreferences to store data:
Future<bool> setUserStatus(String userStatus) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('userStatus', 'active');
return true;
}
Is it possible to use this same setUserStatus in another file, which will get this main.dart imported to it, and change the SharedPreferences data to something else based on the actions taken in the other file
Do this,
await setUserStatus( status );
if you don't want to wait for the future to complete just remove await from the begining.
Calling prefs.clear()will erase all the preferences set on the device. so I would suggest not to use that here. If you want to clear a particular preference just use
prefs.remove(key) or prefs.setString(key,null)

How to update value inside shared preferences in flutter

actually when saving data inside shared preferences.. I am using this code
add() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('data', "ok");
}
but, is there a way to update the value of data for example I want to change ok into fine
because when I try to re-save my data using that code... and call it using prefs.getString('data'); it always shows the old data not the update one
Just reassign it again
prefs.setString('data', "fine");
//shared-preferences
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('profileImg', data1['imagePath']);
prefs.setString('un', data1['username']);