首页 > 解决方案 > 如何在 Flutter dart 中使用共享首选项保存和读取类对象列表?

问题描述

我有以下课程:

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 preferencesdate属性用作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);
}

标签: flutterdartsharedpreferences

解决方案


由于该方法setListString需要SharedPreference一个字符串列表。

保存

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

  1. 将您的Payment实例转换为Map<String, dynamic>
 // payment instance 
 Payment payment = Payment();
 // convert the payment instance to a Map
 Map<String, dynamic> mapObject = payment.toMap();
  1. 编码从步骤 1获得的 `Map<String, dynamic> 的值
 // encode the Map which gives a String as a result
 String jsonObjectString = jsonEncode(mapObject);
  1. 编码结果是String您可以添加到List可以传递给SharedPreference setListString方法的 a 。
  // list to store the payment objects as Strings
  List<String> paymentStringList = [];
  // add the value to your List<String>
   paymentStringList.add(jsonObjectString);

读书

fromMap()1.在您的Payment类中创建一个工厂构造函数,将 a 转换MapPayment对象。

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

  1. Json String_List
 // get the json string from the List
 String jsonObjectString = paymentStringList[2]; // using index 2 as an example
  1. 通过解码将其转换Json String为aMap
 // convert the json string gotten to a Map object
 Map mapObject = jsonDecode(jsonObjectString);
  1. 使用类的fromMap构造函数Payment将其转换MapPayment对象
  // 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);

推荐阅读