【问题标题】:How can i save shared prefrence in list?如何在列表中保存共享偏好?
【发布时间】:2020-04-03 12:54:10
【问题描述】:

我有两个类,在第一类中设置 sharedPrefrence 像这样:

[{"name":"alex","code":"12345"}]

我的共享偏好设置方法:

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

并在二等舱中显示此列表,我想在返回一等舱并输入名称和代码时,将它们添加到以前的列表中(保留以后的数据),如下所示:

[{"name":"alex","code":"12345"},{"name":"john","code":"98765"}]

我该怎么做?

【问题讨论】:

  • 您展示的第二个示例是您想要的? "[{"name":"alex","code":"12345"},{"name":"john","code":"98765"}]" 这只是一个 json 数组......你可以从字面上将您的字符串转换回 Json,附加您的新对象并将整个内容再次保存为字符串

标签: flutter dart


【解决方案1】:

创建Customer 模型:

class Customer{
  Customer({this.name, this.code});

  String name;
  String code;

  Customer.fromMap(json)
    : name = json['name'].toString(),
      code= json['code'].toString();
}

然后,创建一个添加到您的 SharedPreferences 列表中的方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多