How to save data in my settings menu in Flutter? - 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.

Related

remove data inside the key in SharedPreferences

im using flutter 2.8.1 and shared_preferences: ^2.0.13
i build a todoapp with sharedpreferences all works fine from storing data to localstorage and load the data in initState but now i want to delete spesific item/selected item in the localstorage but when i use prefs.remove('key'); all the item is removed, i only want to remove the selected item only.
let me know if you need more information with the code.
the key contain this, for example i want to remove item with id: 64, not the key
I/flutter ( 9643): [{"id":64,"set_name":"asd"},{"id":55,"set_name":"asdasdwqe"}]
remove function code
Future deleteData() async {
final SharedPreferences prefs = await _prefs;
prefs.remove('sets');
setState(() {});
}
save function code
Future saveData() async {
final SharedPreferences prefs = await _prefs;
List items = c.setList.map((item) => item.toJson()).toList();
prefs.setString('sets', jsonEncode(items));
}
There isn't easy way but to overwrite new values over old value. This is one of the drawbacks of using SharedPreferences over traditional databases.
You will have to read the data from sharedPrefs, remove the concerned value and save it back to sharedPrefs.

Read data using from the device as soon as an app opens in flutter

I am saving the app's theme to the device using SharedPreferences, in this way:
void _serializeTheme() async {
SharedPreferences _preferences = await SharedPreferences.getInstance();
_preferences.setString("theme", "dark");
}
Upon opening the app I can use _preferences.getString("theme") to detect the theme, but as SharedPreferences.getInstance() is async, I need to wrap the home of my application in a FutureBuilder which waits for the theme to load before displaying the page and renders a container while waiting. My problem is that for the brief time that the app spends loading the theme the screen flashes with the color of the container which, as I have no idea of which theme the user has saved before loading it, has to be a fixed color which may be in discordance with the background color of the home page. To prevent this is there a way I can load the theme before displaying anything at all?
So, is there a way to run an asyncronous function before opening the application? Or if this isn't fiesable, is there a way to read data syncronously from the device so that I could read it inside initState() so that I can know the theme that the user saved before rendering anyting?
In your case, I would get await data in before runApp(),
Example:
main()async{
// Here
SharedPreferences _preferences = await SharedPreferences.getInstance();
runApp(YourApp());
}
or
void main() {
runZonedGuarded(() async {
// Here
SharedPreferences _preferences = await SharedPreferences.getInstance();
runApp(YourApp());
}, (_, s) {});
}
You have to show something. You can set a splash screen of your choice using https://pub.dev/packages/flutter_native_splash, and then use that same screen to show when the FutureBuilder doesn't yet have the completed future, before transitioning to your main theme when it's ready.

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.
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.

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']);