Flutter : How to use SharedPreference to get List<String>? - flutter

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);
}

Related

How to initialize SharedPreferences 2.0.15 in flutter? (Dart - Flutter)

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

How to retrieve data from Future object properly?

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 ?? [];
}

How to save a list to shared preferences

I want to save a list to shared preferences, but it doesn't work... The goal is to add data to the variable and save it.
This is the variable I want to save:
var savedData = [
{'date': 0, 'testNumber': 0},
];
And this is the code I tried for saving and receiving the variable:
Future<void> saveDataTest() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList(
'dataTest', savedData.map((i) => i.toString()).toList());
}
Future<String> getDataStringTest() async {
final prefs = await SharedPreferences.getInstance();
savedData =
prefs.getStringList('dataTest').map((i) => int.parse(i)).toList();
setState(() {});
}
This is the error I get:
A value of type 'List<int>' can't be assigned to a variable of type 'List<Map<String, int>>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Map<String, int>>'.
As you are using in your list a Map object with primitive types, you can use jsonEncode and convert to a String that can be saved in sharedPreferences and use jsonDecoder when want to revert.
like this:
String toBeSaved = jsonEncode(savedData);
prefs.setString('dataTest', toBeSaved);
Try using jsonEncode and jsonDecode from import 'dart:convert';
Like so:
Future<void> saveDataTest() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString("dataTest ", jsonEncode(savedData));
}
Future<String> getDataStringTest() async {
final prefs = await SharedPreferences.getInstance();
savedData = List.from(jsonDecode(prefs.getString("dataTest")));
setState(() {});
}

Flutter: Save and Fetching multiple value in SharedPreferences

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.

Instance of 'Future<String>' instead of showing the value

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.