How can i save shared prefrence in list? - flutter

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

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

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

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

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

How to save a string in a Liststring in flutter?

Hello I don't find a solution to add a string in a liststring that I can save with shardpref.
I have a specific case where I use QR code reader, the output is a string that I want to store in a Liststring and save with sharedpref
Here is the part of the plugin who generate the String code of the QRcode:
void _onQRViewCreated(QRViewController controller) {
final channel = controller.channel;
controller.init(qrKey);
this.controller = controller;
channel.setMethodCallHandler((MethodCall call) async {
switch (call.method) {
case "onRecognizeQR":
dynamic arguments = call.arguments;
setState(() {
qrText = arguments.toString();
qrText is a String. I tried to change argments.toListstring(); but I have no output when I did this ...
Here is my save List function where I can't add qrText to the Stringlist
save_code() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setStringList("save_code",qrText); // qrText need to be a Stringlist
_my_save_code_list = prefs.getStringList("save_code");
} );
}
Thank you
Why do you want to use a StringList? If it is only the code you could also save it as a normal string, right? Or is the string too long to be a normal string?
-> I think you need to do it like this:
save_code() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> stringList = [];
stringList.add(qrText);
setState(() {
prefs.setStringList("save_code",stringList); // qrText need to be a Stringlist
_my_save_code_list = prefs.getStringList("save_code");
} );
}