我有以下类(class):
class Payment {
String date;
String time;
String code;
String toPay;
String payed;
String left;
Payment({ this.date, this.code, this.toPay, this.payed, this.left, this.time });
}
在我的Flutter App中,我应该使用payments
保存并读取shared preferences
列表,并将date
属性用作key
_ReadPayment(String date) async {
final prefs = await SharedPreferences.getInstance();
final key = date;
// here how i get the list of payment like getPaymentList instead of getStringList
final value = prefs.getStringList(key) ?? null;
}
_SavePayment(String date, List<Payment> list) async {
final prefs = await SharedPreferences.getInstance();
final key = date;
// here how i set Payment list instead of setStringList
prefs.setStringList(key,list);
}
最佳答案
由于setListString
的SharedPreference
方法采用字符串列表。
要保存
toMap()
类中创建方法Payment
,该方法将Payment
对象转换为Map
。 class Payment {
String date;
String time;
String code;
String toPay;
String payed;
String left;
Payment({
this.date,
this.code,
this.toPay,
this.payed,
this.left,
this.time,
});
// method to convert Payment to a Map
Map<String, dynamic> toMap() => {
'date': date,
'time': time,
....// do the rest for other members
};
}
Payment
实例转换为Map<String, dynamic>
// payment instance
Payment payment = Payment();
// convert the payment instance to a Map
Map<String, dynamic> mapObject = payment.toMap();
// encode the Map which gives a String as a result
String jsonObjectString = jsonEncode(mapObject);
String
,您可以将其添加到List
中,然后将其传递给SharedPreference
setListString
方法。 // list to store the payment objects as Strings
List<String> paymentStringList = [];
// add the value to your List<String>
paymentStringList.add(jsonObjectString);
要阅读
1.在
fromMap()
类中创建工厂构造函数Payment
,将Map
转换为Payment
对象。class Payment {
String date;
String time;
String code;
String toPay;
String payed;
String left;
Payment({
this.date,
this.code,
this.toPay,
this.payed,
this.left,
this.time,
});
// factory constructor to convert Map to a Payment
factory Payment.fromMap(Map<String, dynamic> map) => Payment(
date: map['date'],
time: map['time'],
.... // other members here
);
Json String
获取List
// get the json string from the List
String jsonObjectString = paymentStringList[2]; // using index 2 as an example
Json String
,将其转换为Map
// convert the json string gotten to a Map object
Map mapObject = jsonDecode(jsonObjectString);
fromMap
类的Payment
构造函数将Map
转换为Payment
对象 // use the fromMap constructor to convert the Map to a Payment object
Payment payment = Payment.fromMap(mapObject);
// print the members of the payment class
print(payment.time);
print(payment.date);
关于flutter - 如何使用Flutter dart中的共享首选项保存和读取类对象的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63863854/