flutter add value to list - flutter

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

Related

Issues with flutter futures - map results in List<Future>

I'm having issues with the return type of this HTTP request, I need to return Future<List> but the map is returning a List<Future>. I don't know how to get the CustomerInfo without it being a future and I don't know how to return it any other way.
if (response.statusCode == 200) {
Iterable l = json.decode(response.body);
final data = List.from(l.map((model) async {
final name = model['UserName'];
final id = model['UserICode'];
return {name, id};
}));
final users = data.map<CustomerInfo>((e) async {return await getFaxinfo(e.id, e.name);});
return users;
} else {
throw 'err';
}
}
Future<CustomerInfo> getFaxinfo(
String id,
String name,
) async {
final baseUrl = 'localhost';
final int port = 3003;
final accountsPath = '/accounts';
final accountsFaxInfoPath = '$accountsPath/fax-info';
final Map<String, dynamic> queryParam = {'id': id};
final uri = Uri(
scheme: 'http',
path: accountsFaxInfoPath,
host: baseUrl,
queryParameters: queryParam);
final response = await http.get(uri);
return CustomerInfo(sent: 200, received: 300, name: 'Test');
}
The problem is that an async function always returns a Future no matter if you call await inside it or not. To fix it a good approach is to use list comprehension. A simple for loop also would do.
Instead of those 2 maps that result in List<Future>:
final data = List.from(l.map((model) async {
final name = model['UserName'];
final id = model['UserICode'];
return {name, id};
}));
final users = data.map<CustomerInfo>((e) async {return await getFaxinfo(e.id, e.name);});
Do the following with list comprehension:
final users = [
for (final model in l)
await getFaxinfo(model['UserICode'], model['UserName'])
];
Now if you want to make the HTTP calls in parallel it's possible to do a Future.wait() in a List<Future> to get the result as List<CustomerInfo>. Something like the following:
final users = await Future.wait(l.map((model) async =>
await getFaxinfo(model['UserICode'], model['UserName'])));

Problem with filling the list after await command

I have just started Flutter and I am stuck at a point. Below is some part of my function that first uploads provided pictures on firebase storage and then get their downloadable URLs and store them in the list of string. It should upload data to firestore with the list of URLs obtained from command list.add(imageUrl);
List<String> list = [];
imgList.forEach((element) async {
final String filePath = element.path;
final res =
filePath.substring(filePath.lastIndexOf('im'), filePath.length);
final ref = FirebaseStorage.instance.ref().child('images').child(res);
await ref.putFile(File(element.path));
final imageUrl = await ref.getDownloadURL();
list.add(imageUrl);
});
final doc = FirebaseFirestore.instance.collection('cars').doc();
but it doesn't happens because the following line is called before filling the list due to await.
await doc.set({
'id': doc,
'img': list,
'price': 14450,
'make': 'Toyota',
'year': 2015`
});
Add await before imgList.forEach like
List<String> list = [];
await imgList.forEach((element) async {
final String filePath = element.path;
final res =
filePath.substring(filePath.lastIndexOf('im'), filePath.length);
final ref = FirebaseStorage.instance.ref().child('images').child(res);
await ref.putFile(File(element.path));
final imageUrl = await ref.getDownloadURL();
list.add(imageUrl);
});
final doc = FirebaseFirestore.instance.collection('cars').doc();
edit
if this doesn't work then you may use for loop instead of forEach like
List<String> list = [];
for(var element in imgList) {
final String filePath = element.path;
final res =
filePath.substring(filePath.lastIndexOf('im'), filePath.length);
final ref = FirebaseStorage.instance.ref().child('images').child(res);
await ref.putFile(File(element.path));
final imageUrl = await ref.getDownloadURL();
list.add(imageUrl);
}
final doc = FirebaseFirestore.instance.collection('cars').doc();

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 to get all content from Shared Preferences in 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));
});
});

How can i save shared prefrence in list?

i have two class , in first class set sharedPrefrence like this :
[{"name":"alex","code":"12345"}]
my shared prefrence set method :
Future _shared() async {
final _customer = {
"name": _controller1.text,
"code": _controller2.text,
};
List<Map<String, dynamic>> customers = [];
customers.add(_customer);
final customerEncode = jsonEncode(customers);
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString("list_customer", customerEncode);
print(customerEncode);
}
and show this list in second class , i want when back to first class and enter name and code , they are add to previous list(keep later data) like this :
[{"name":"alex","code":"12345"},{"name":"john","code":"98765"}]
how can i do this ?
Create Customer Model:
class Customer{
Customer({this.name, this.code});
String name;
String code;
Customer.fromMap(json)
: name = json['name'].toString(),
code= json['code'].toString();
}
Then, create a method which adds into your SharedPreferences list:
addIntoList(Customer obj){
List<Customer> customersList = new List();
SharedPreferences pref = await SharedPreferences.getInstance();
// get list from SharedPreferences
var customers = pref.getString("list_customer");
var customersDecode = jsonDecode(customers);
// loop through your saved array and get them into customersList
customerDecode.forEach((val) {
customersList.add(Customer.fromMap(val));
});
// at last, add your parameter object
customersList.add(obj);
// save list to SharedPreferences
pref.setString("list_customer", jsonEncode(customersList));
}