How to get all content from Shared Preferences in flutter - flutter

I want to get all sharedprefrences content (key,value).Is it possibly?Is there a possibility to iterate by keys?
getStringValues() async
SharedPreferences prefs = await SharedPreferences.getInstance()
String stringValue = prefs.getString('key');
return stringValue;
}

Use SharedPreferences.getKeys() to get all keys and then get their values with a for loop like this:
final prefs = await SharedPreferences.getInstance()
final keys = prefs.getKeys();
final prefsMap = Map<String, dynamic>();
for(String key in keys) {
prefsMap[key] = prefs.get(key);
}
print(prefsMap);

SharedPreferences.getInstance().then((data){
data.getKeys().forEach((key){
print(key+"="+data.get(key));
});
});

Related

Flutter shared prefernce return NULL

I have next piece of flutter code, to get shared preference key-value
I do understand why _blueUriInit is always NULL
I assume that you are forgot to provide the value for that key before call to get its value, you need to first assign value to it first:
Future<bool> saveData(String key, dynamic value) async {
final prefs = await SharedPreferences.getInstance();
return prefs.setString(key, value);
}
and call it like this:
void initState() {
saveData('blueUri', 'test');
setState(() {
_blueUriInit = getValue('blueUri');
});
super.initState();
}
now next time you open your app, getValue should return you test.
you can create this function for setting value
static setUserID(String key, String value) async {
final SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setString(key, value);
}
Use case :
await SharedValue.setUserID("Email", "demo#gmail.com");
And For getting value from shared preference you can use this function
static Future<String?> getUserID(String key) async {
final SharedPreferences preferences = await SharedPreferences.getInstance();
return preferences.getString(key);
}
Use case :
userName = await SharedValue.getUserID("Email");
First you need to setString with key and value (name is key)
Future setValue() async {
final prefs = await SharedPreferences.getInstance();
prefs.setString("name", "Hitarth");
}
getString with key (here i took "name" as key)
Future getValue(String key) async {
final prefs = await SharedPreferences.getInstance();
String value = prefs.getString(key) ?? "NULL";
return value;
}
store in variable callin getValue
void initState() {
setState(() {
_blueUriInit = getValue("name");
});
super.initState();
}

How can I make this work? My shared preferences seem to store the wrong value?

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

is there way to get a particular data which have been saved using shared preference?

#i Saved all my user data using shared preference to perform autologin and it works well data is saved
token = responseData['token'];
userEmail = responseData['user_email'];
userNicename = responseData['user_nicename'];
userDisplayName = responseData['user_display_name'];
userAddress = responseData['user_address'];
userContact = responseData['user_contact'];
userId = responseData['user_id'];
userDisplayUrl = responseData['user_display_url'];
notifyListeners();
SharedPreferences prefs = await SharedPreferences.getInstance();
final userData = jsonEncode({'token':token,'user_email':userEmail,'user_nicename':userNicename,'user_display_name':userDisplayName,'user_address':userAddress,'user_contact':userContact,'user_id':userId,'user_display_url':userDisplayUrl});
prefs.setString('userData',userData);
#Data is saved in this manner
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvc3dlZXQtYXJkaW5naGVsbGkuMy0xMDgtMTM4LTIwNi5wbGVzay5wYWdlIiwiaWF0IjoxNjQyMzMwNzQyLCJuYmYiOjE2NDIzMzA3NDIsImV4cCI6MTY0MjkzNTU0MiwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMjgifX19.2jZEu-QNL3UxRiFSgVE728bF_cl_CZd0VJLT1f5HfCc","user_email":"sauravadhikari404#gmail.com","user_nicename":"sauravadhikari404","user_display_name":"SauravAdhikari404","user_address":null,"user_contact":null,"user_id":"28","user_display_url":""}
#now i wanna access single single data like i wanna get that user_id only or user_email only but i dont know how to do it i tried like this
String? userData;
#override
void initState(){
// TODO: implement initState
getUserId();
super.initState();
}
void getUserId()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
userData = prefs.getString("userData");
print(userData);
});
}
#as i mentioned above all my data is comming in userData but now i wanna fetch my user_id only or user_email but i am unable to
Use jsonDecode to convert it to a Map:
Like so:
setState(() {
var userId = jsonDecode(prefs.getString("userData"))["user_id"];
print(userId);
});
To handle the null case:
String? userDataString = prefs.getString("userData");
if(userDataString != null){
var userId = jsonDecode(userDataString)["user_id"];
var email = jsonDecode(userDataString)["user_email"];
}

how can i store multiple data in sharedpreferences?

I am getting user information like the username , profile pic and name .I want to store all that info inside Sharedpreferences so that i wont have to call firebase every time I need them.
here is how i am getting the data ,how can i store this data so that later on i can get user's name and its profilepic by checking it through its username ?
storeUsersInfo()async{
print('STORE CALLED');
QuerySnapshot querySnapshot = await DatabaseMethods().getUsers();
var length = querySnapshot.docs.length ;
print(length);
int i = 0 ;
while ( i < length ) {
print(name = "${querySnapshot.docs[i]["name"]}");
print(profilePicUrl = "${querySnapshot.docs[i]["profileURL"]}");
i++;
}
}
here is the firebase call
Future<QuerySnapshot> getUsers() async {
return await FirebaseFirestore.instance
.collection("users")
.get();
}
and if anyone needs anything else please ask .
You can store all the information in SharePreference by encoding picture objects to Base64String before storing them.
How you can encode it:
Future<String> encodeImageToBase64String(String imageUrl) async {
final response = await client.get(Uri.parse(imageUrl));
final base64 = base64Encode(response.bodyBytes);
return base64;
}
After Encoding the image, you can cache it to sharedPreference using
SharedPreferences pref = await SharedPreferences.getInstance();
//Save string to SharedPreference
pref.setString('image', encodedImageString);
How to Decode and use Image Later
//Get Encoded Image String from SharedPreferences
final base64String = pref.getString('image');
///Decodes Images file encoded to Base64String to Image
Uint8List decodeImageFromBase64String(String base64String) {
return base64Decode(base64String);
}
Finally, you can use this in your Image Widget like so
...
Image(image: MemoryImage(decodeImageFromBase64String))
Assuming you want to cache name, username and image gotten from firebase
//Create a model for the firebase data
class UserModel{
final String name;
final String username;
final String encodedImage;
UserModel(this.name, this.username, this.encodedImage);
String toJson(){
Map<String, dynamic> userMap = {
'name': name,
'username': username,
'image': encodedImage,
};
return json.encode(userMap);
}
}
//Encode the image HERE
encodeImageToBase64String(imageUrl);
//Pass in the parameters to the UserModel() constructor and Call //the toJson(), then Cache the Resulting String
String stringToCache = UserModel(nameString, usernameString, encodedImageString).toJson();
SharedPreferences takes a key and the data.
use this in an async funtion.
This syntax is sharedPreferences.setString(key, value)
So in a function,
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString("token", jsonResponse['access_token'].toString());
sharedPreferences.setString("userId", jsonResponse['customer_id'].toString());
You can get the stored data by sharedPreferences.getString(key).Like
var token = sharedPreferences.getString("token");
You can use a cache like https://pub.dev/packages/firestore_cache which does that for you.

flutter add value to list

i set object like this : {"name":"alex","code":"123"}
into sharedPrefrence Calss A:
var resBody = {};
resBody["name"] = name.text;
resBody["code"] = pass.text;
str = json.encode(resBody);
print(str);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("list_customer", str);
and when get this sharedPrefrence in another class
add value of shared to the list Class B:
customer = (prefs.getString('list_customer'));
Map<String, dynamic> user = jsonDecode(customer);
_customer.nameFamily = user['name'];
_customer.code = user['code'];
_list.add(_customer);
and i want to know how can i set new value of shared into the previous list like this :
[{"name":"alex","code":"123"},{"name":"john","code":"128"}]
To store multiple customers, you need a List not Map.
Declare a List
List<Map<String, dynamic>> customers = [];
Add object(s) to the list
final customer = {
"name": name.text,
"code": pass.text,
};
customers.add(customer);
Stringfy (encode) customers list
final customersString = json.encode(customers);
Store encoded customers list
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("list_customer", customersString);
Let's say you store one customer, and now you need to store another.
we get customers list first, then we decode it
String customersString = await prefs.getString('list_customer');
final customers = json.decode(customersString);
Add the new object to the list (previous step #2)
customers.add({
"name": 'Amir',
"code": 'SWF2022',
});
Repeat step #3 and #4.
Good luck
Check example below
Future saveGetValues() async {
const key = 'list_customer';
var list = <Map<String, String>>[];
list.add(createValue('name1', 'code2'));
//save first time
save(key, list);
list = await getValue<List<Map<String, String>>>(key); //here your saved list
//add second value
list.add(createValue('name2', 'code2'));
save(key, list);
list = await getValue<List<Map<String, String>>>(key); //here your saved list with two items
}
Map<String, String> createValue(String name, String code) {
final resBody = <String, String>{};
resBody["name"] = name;
resBody["code"] = code;
return resBody;
}
Future save(String key, dynamic value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, jsonEncode(value));
}
Future<T> getValue<T>(String key) async {
final prefs = await SharedPreferences.getInstance();
return json.decode(prefs.getString(key)) as T;
}