由于SharedPreference 的方法setListString 采用一个字符串列表。
保存
- 在
Payment 类中创建一个方法toMap(),将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();
- 对 步骤 1 获得的 `Map 的值进行编码
// encode the Map which gives a String as a result
String jsonObjectString = jsonEncode(mapObject);
- 编码后的结果是一个
String,您可以将其添加到一个List 中,该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.在Payment 类中创建工厂构造函数fromMap(),将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
);
- 从
List 获取Json String
// 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);
- 使用
Payment 类的fromMap 构造函数将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);