颤振 - 如何将列表保存到<Object>共享首选项中?



我想将产品添加到购物车并保存它,这样当我再次打开应用程序时,它就会出现在购物车中。我可以将多个产品添加到购物车中,所以我想保存一个List<Products>

我想将列表保存到sharedPreferences中并检索相同的列表,但没有相应的方法。我尝试使用setStringList,但无法将字符串转换为对象。数据也没有被保存。

我的班级模型-

import 'dart:convert';
class Products {
Products({
required this.title,
required this.price,
required this.description,
required this.image,
this.quantity = 0,
});
final String title;
final double price;
final String description;
final String image;
int quantity;
factory Products.fromRawJson(String str) =>
Products.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Products.fromJson(Map<String, dynamic> json) => Products(
title: json["title"],
price: json["price"].toDouble(),
description: json["description"],
image: json["image"],
);
Map<String, dynamic> toJson() => {
"title": title,
"price": price,
"description": description,
"image": image,
};
}

shared_preferences库只有保存以下内容的选项。

  • int
  • 字符串
  • 列表
  • 双重
  • 布尔值

参考:https://pub.dev/documentation/shared_preferences/latest/shared_preferences/SharedPreferences-class.html

但是你可以做的是以jsonEncode的形式创建一个List<String>并保存它

通过使用对每个列表进行编码,将列表转换为列表https://api.flutter.dev/flutter/dart-convert/jsonEncode.html

完成后,您可以保存它,并在解码时类似地使用jsonDecode

希望这能有所帮助。谢谢

import 'dart:convert'; 
//first converts your array to json string store it in session   
String strJsonString = json.encode(arrayProducts); 
//save strJsonString as String into your session

//when you want to retrive it from session just decode session value
List<Products> = json.decode(strJsonString);

相关内容

最新更新