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.
Related
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} <==');
}
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.
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)
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']);
I search how to make an action for each call of the initstate of my statefull widget exept the first call.
Thank you
The best method would be to use the SharedPreferences plugin which saves values to local storage.
Add the dependency to your pubspec.yaml file
dependencies:
shared_preferences: ^0.5.6
Import the plugin
import 'package:shared_preferences/shared_preferences.dart';
Reference the SharedPreferences class
SharedPreferences prefs = await SharedPreferences.getInstance();
Lastly check if it is the first time or not
// If the preference firstTime does not exist it means it is the first time
bool firstTime = prefs.getBool('firstTime') ?? true;
if(firstTime){
// This is the first time the user is opening the app
// Set firstTime preference value to false
await prefs.setBool('firstTime', false);
} else{
// The app has been opened before
}