Flutter: Save and Fetching multiple value in SharedPreferences - flutter

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.

Related

How to store data in shared preference when retrieve from database firestore in flutter?

In my code at the home page fetch user name from firestore database and that's display nicely in UI. I want pass that name to shared preference function and store there and use that name in another pages also.
Code
home page code ( initstate and send name to saveNameToSharedPreferences() method )
#override
void initState() {
super.initState();
getData();
fetchName();
storeName();
}
void storeName() {
String displayName = '${user?.displayName}';
return displayName.saveNameToSharedPreferences();
}
SharedPreferences code
import 'package:shared_preferences/shared_preferences.dart';
String? _displayName;
String? get displayName => _displayName;
Future saveNameToSharedPreferences() async {
final SharedPreferences sn = await SharedPreferences.getInstance();
await sn.setString('displayName', _displayName!);
}
Future getNameFromSharedPreferences() async {
final SharedPreferences sn = await SharedPreferences.getInstance();
_displayName = sn.getString('displayName');
}
How to solve this ?
You are calling function as an extension. Try to pass parameter instead.
Make the following changes
Future saveNameToSharedPreferences(String displayName) async {
final SharedPreferences sn = await SharedPreferences.getInstance();
await sn.setString('displayName', displayName);
}
And call it as
void storeName() {
String displayName = '${user?.displayName}';
saveNameToSharedPreferences(displayName);
}

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

why doesn't flutter update the status of my widgets?

I am using the shared_preferences within my app to save some data
but they only update the second time I open them
prefs.setInt is Future method, try putting await before all of it.
async{
final prefs = await SharedPreferences.getInstance ();
///others
await prefs.setInt ('s$current month $current year', s);
setState (() { });
}
And create another method to fetch data on initState like
fetchData()async{
final prefs = await SharedPreferences.getInstance ();
hours = prefs.getInt(...);
///....
setState(() { });
}
#override
void initState() {
super.initState();
fetchData();
}

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

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

How to init state of widget variable with Future string in flutter

I have to initialise the state of widget variable with the value stored in StoredProcedure.
void initState() {
widget.query = fetchMake();
super.initState();
}
Future<String> fetchMake() async{
final prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
query.toString();
}
But the issue is that it cant assign that value to query variable and showing error value to type future string cannot assign to string flutter
How can I do that?
fetchMake is async so you have to put await where you call that method but it will not work because you are calling it in initState.
So You have to assign widget.query variable value in that function only. Moreover, as you get data you have to call setState, so data you receive reflect in ui.
In addition to that you have to check query is null or not where you are using it because when first time build method call it will not have any data.
String query;
void initState() {
fetchMake();
super.initState();
}
fetchMake() async{
final prefs = await SharedPreferences.getInstance();
setState((){
query = prefs.getString(key) ?? 'default';
});
}
You can try:
String query;
void initState() {
super.initState();
fetchMake().then((value) {
setState(() {
query = value;
});
});
}
Future<String> fetchMake() async{
final prefs = await SharedPreferences.getInstance();
return prefs.getString(key);
}
1, You can not set state with widget.query.
2, Create a variable query on state of Widget.
3, fetchMake is a async function => using then to wait result.