so newbie question but i think i have done everything in accordance with the documentation and i can't find the bug i have List string with shared preferences and 3 function laod save delete ,load and save work perfect but delete doing nothing without errors :/
List favorites=[];
#override
void initState(){
super.initState();
setState(() {
_loadList();
});}
_loadList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
favorites = (prefs.getStringList('myFavorites') ?? []);
});
}
_saveList(documentID) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList('myFavorites', ['$documentID']);
_loadList();
}
_deleteList(documentID) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var list= prefs.getStringList('myFavorites');
list.remove(documentID);
_loadList();}
I couldn't find too many questions about it, I think my own stupidity forgets something. can someone help ?
I made a new list and add all keys to new list. deleted documentId in my new list and put the new list in place of myFavorites. Also works.
Related
I am using shared_preferences: ^2.0.15 and saving my values locally.
When I change my screen and get my values, I get an error.
How can I initialize SharedPreferences correctly?
Video
late SharedPreferences _preferences;
#override
void initState() {
super.initState();
getLocalData();
}
Future getLocalData() async {
_preferences = await SharedPreferences.getInstance();
}
I've checked the video you shared.
You're just missing to call the getLocalData method inside the LoginViewModel.
I'd suggest adding a line inside your loginRequest method to call getLocalData method. Well, don't forget to await.
await getLocalData();
That's it :)
actually you are not fetching data from your shared preference
you have to get the data that u saved
first set data that you want to save
addStringToSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('email', "email#email.com");
}
then in your second screen you can get your data
late SharedPreferences _preferences;
late String email;
#override
void initState() {
super.initState();
getLocalData();
}
Future getLocalData() async {
_preferences = await SharedPreferences.getInstance();
// for exemple you saved a string value with key ='email'
email= _preferences.getString('email');
}
check this : https://medium.flutterdevs.com/using-sharedpreferences-in-flutter-251755f07127
I am having trouble identifying as to why setState() is returning null on my shared preferences getString method.
I am calling an async function outside of the initState and the constantly printing null when i check the return string of getString on page load.
I have checked that setString is saving the correct string to the key.
Here is my code:
void initState() {
super.initState();
retrieve();
}
retrieve() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
name = prefs.getString("displayName");
print(name);
});
}
Here is where I setString(in the register user page):
try {
UserCredential result =
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
final user = FirebaseAuth.instance.currentUser;
final name = _usernameController.text;
// if (user != null) {
await user?.updateDisplayName(name);
Navigator.pushNamed(context, homeRoute);
print(name);
You should set ,username via shared preference before accessing it.
final prefs = await SharedPreferences.getInstance();
In register page.(where you want to set name via SharedPreference before accessing it)
await prefs.setString('displayName', 'name');
After setting it in registeration you can access like above
name = prefs.getString("displayName");
When SharedPreferences return null value it means you have not set value with your key yet. So firstly set something like this:
final prefs = await SharedPreferences.getInstance().reload();
await prefs.setString('displayName', 'Mark');
then try to call it.
Thanks to all who have spent the time to respond to help. I hope this answer might help some one else down the track.
I found that Shared Preferences was not saving the data - my code was fine after all. I simply just closed the app and restarted the X code build from scratch and it is now working.....
I'm using shared preferences. I want to get the list of strings, but for some reason it's always a null though it shouldn't be. I think I'm making a mistake in asynchronous stuff. Can somebody help me? With explanation if possible.
List<String> getSaved() {
List<String>? items;
Future<SharedPreferences> prefs = SharedPreferences.getInstance();
prefs.then((prefs) async {
items = prefs.getStringList('saved');
});
// SharedPreferences prefs = await SharedPreferences.getInstance();
// items = prefs.getStringList('saved');
return items ?? [];
}
Because you want the result when the future completed your function should be of type Future<List<String>> and you can use then or await knowing that items should be of the same type too
Future<List<String>> getSaved() async {
List<String>? items;
SharedPreferences prefs = await SharedPreferences.getInstance();
items = prefs.getStringList('saved');
// SharedPreferences prefs = await SharedPreferences.getInstance();
// items = prefs.getStringList('saved');
return items ?? [];
}
I've create an initState in my page and call callData to get favId (type : List) every I open this page. But, when the application start, my compiler show this error message :
_TypeError (type 'List<String>' is not a subtype of type 'String')
and this is my getData's function :
getData(favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favId);
}
also this is my saveData's function :
void saveData() async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList("id", favId);
}
How to fix this problem and I can call getData every I open this page in my application?
Thank you :)
if you want to save and retrieve List to and from SharedPreferences, you to use same key to save and retrieve the value.
here is a simple example,
const favKey = 'favoriteKey';
To save data,
void saveData(String favKey, List<String> favorites) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList(favKey,favorites);
}
To retrive data,
getData(String favKey) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favKey);
}
Note: You need to use same key to set and get data using SharedPreference.
"id" is a String, you need to store a List<String> into setStringList
There are the steps if you want to add an item to the list:
List<String> ids = await getData(favId);
ids.add("id");
saveData(ids, favId);
then change the saveData() to
void saveData(ids, favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList(ids, favId);
}
getData()
List<String> getData(favId) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getStringList(favId);
}
I'm working with SharedPreferences to make feature offline bookmark News . i can saved and fetching single value with this code :
Saved Value
void _testingSavePref(String judulBerita) async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString("tokenbookmark", judulBerita);
}
Fetching Value
#override
void initState() {
super.initState();
setState(() {
_testingLoadPref();
});
}
_testingLoadPref() async {
SharedPreferences pref = await SharedPreferences.getInstance();
setState(() {
tokenBookmark = pref.getString("tokenbookmark");
});
}
Everything is oke , but it's possible to saved and fetching multiple value with SharedPreferences ?
Example, i have 2 or more data, i want all data saved and not overwrite.
Thank's
Updated Code:
For Saving Values
void _testingSavePref(List<String> judulBerita) async {
SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setStringList("tokenbookmark", judulBerita); //judulBerita is a list of string now
}
For Fetching Values
#override
void initState() {
super.initState();
setState(() {
_testingLoadPref();
});
}
_testingLoadPref() async {
SharedPreferences pref = await SharedPreferences.getInstance();
setState(() {
final List<String>? tokenBookmark = pref.getStringList("tokenbookmark");
});
}
Now, You can get the data from tokenBookmark list by below code
for(String s in tokenBookmark){
print(s);
}
You shouldn't use SharedPreferences to save that kind of data.
Use a local sql or nosql database (sqflite / sembast).
Also don't call setState inside the initState method is wrong and unnecessary.