我有下面的类设置。我能够存储JSON,但检索它时遇到问题。
import 'package:flutter/material.dart';
class SvItem with ChangeNotifier {
final String id;
final String meatType;
final String meatTypeImg;
final String meatCut;
final String duration;
final String temperatur;
final List<String> instructions;
final String notes;
bool isFavorite;
SvItem({
required this.id,
required this.meatType,
required this.meatTypeImg,
required this.meatCut,
required this.duration,
required this.temperatur,
required this.instructions,
required this.notes,
this.isFavorite = false,
});
factory SvItem.fromJson(Map<String, SvItem> json) {
return SvItem(
id: "id",
meatType: "meatType",
meatTypeImg: "meatTypeImg",
meatCut: "meatCut",
duration: "duration",
temperatur: "temperatur",
instructions: "instructions" as List<String>,
notes: "notes",
isFavorite: "isFavorite" as bool,
);
}
Map<String, dynamic> toJson() {
return {
"id": id,
"meatType": meatType,
"meatTypeImg": meatTypeImg,
"meatCut": meatCut,
"duration": duration,
"temperatur": temperatur,
"instructions": instructions,
"notes": notes,
"isFavorite": isFavorite
};
}
}
通过这段代码,我可以在sharedpreferences中保存自定义类的示例。
Future saveCustomRecipes(item) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("customRecipesList", jsonEncode(item));
setState(() {});
}
saveCustomRecipes(customRecipes);
但是我如何检索它并将其保存在customRecipes中呢?
我尝试了以下方法:
getCustomRecipesValues() async {
customRecipes = await getCustomRecipesState();
setState(() {});
}
Future getCustomRecipesState() async {
final prefs = await SharedPreferences.getInstance();
var recipeData = prefs.getString("customRecipesList");
List<SvItem> customRecipes =
SvItem.fromJson(jsonDecode(recipeData!)) as List<SvItem>;
print(customRecipes);
return customRecipes;
}
但我得到一个错误:[错误:flutter/运行时/dart_vm_initializer.cc(41)]未处理的异常:类型“List”不是类型“Map〈String,dynamic〉”的子类型
2条答案
按热度按时间7kqas0il1#
当你使用jsonDecode(recipeData!)时,它会得到一个Map而不是List。
尝试转换代码:
变成这样:
为什么你使用jsonEncode而不是你模型类中的toJson方法?
m2xkgtsf2#
你说你传递了一个
List<SvItem>
给这个函数。所以你可以循环遍历这个列表,把每个项目都转换成json。然后你把json对象添加到另一个列表中,并对它进行编码。试试这个:
以及