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 ?? [];
}
Related
i do same exactly as youtube says but in the end i got this error, do you know what is the problem ?
im using flutter 2.8.1 shared_preferences: ^2.0.13
this is the code
class _AppHomeState extends State<AppHome> {
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future loadData() async {
final SharedPreferences prefs = await _prefs;
var stringSet = await prefs.getString('sets');
List setList = jsonDecode(stringSet!);
for (var sets in setList) {
c.setList.add(SetModel().fromJson(sets));
}
}
Future saveData() async {
final SharedPreferences prefs = await _prefs;
List items = c.setList.map((e) => e.toJson()).toList();
prefs.setString('sets', jsonEncode(items));
}
try running
flutter clean
see issue here
Modify line number 31 as below:
final SharedPreferences _prefs = SharedPreferences.getInstance();
This will fix your problem.
I have these functions to set, remove etc variables I want globally available. I fear it might be just a small mistake on my behalf. What can I do to fix this?
static setUserId(userId, value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('userId', value);
}
static getUserId() async {
final prefs = await SharedPreferences.getInstance();
prefs.getInt('userId') ?? 0;
}
static removeUserId() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('userId');
}
static removeAllPreferences() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
}
var userId = user.id;
var value = userId?.toInt();
AccountPreferences.setUserId('userId', value);
var companyId = user.role![0].companyId;
var test = AccountPreferences.getUserId();
print(test); ```
When I run the code above all I print out is an instance of Future<dynamic>?
What am I doing wrong?
You should also await when getting the value and for that, you should declare the function getUserId() as Future and also return the function value like this:
static Future<int> getUserId() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt('userId') ?? 0;
}
var test = await AccountPreferences.getUserId(); // await inside here too, where you call it
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);
}
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.
Iam using flutter and I am trying to get a value from shared_preferences that I had set before, and display it in a text widget. but i get Instance of Future<String> instead of the value. here is my code:
Future<String> getPhone() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String patientPhone = prefs.getString('patientPhone').toString();
print(patientPhone);
return patientPhone;
}
Future<String> phoneOfPatient = getPhone();
Center(child: Text('${phoneOfPatient}'),))
There is await missing before prefs.getString( and use setState() instead of returning the value. build() can't use await.
String _patientPhone;
Future<void> getPhone() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String patientPhone = await /*added */ prefs.getString('patientPhone');
print(patientPhone);
setState(() => _patientPhone = patientPhone);
}
build() {
...
Center(child: _patientPhone != null ? Text('${_patientPhone}') : Container(),))
}
If you don't have the option to use await or async you can do the following.
getPhone().then((value){
print(value);
});
and then assign a variable to them. From that, you'll have the result from the value.