【发布时间】:2021-10-23 00:46:00
【问题描述】:
按照教程并一直遵循它,但现在它没有从资产本地加载 JSON 文件并显示此错误 错误:需要一个“Item”类型的值,但得到一个“_JsonMap”类型的值 我试图解决它,但我不能 这是我正在使用的文件
目录
class CatalogModel {
static List<Item> items = [
Item(
id: "Codepur001",
name: "iPhone 12 Pro",
desc: "Apple iPhone 12th generation",
price: 999,
color: "#33505a",
image:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRISJ6msIu4AU9_M9ZnJVQVFmfuhfyJjEtbUm3ZK11_8IV9TV25-1uM5wHjiFNwKy99w0mR5Hk&usqp=CAc"),
];
}
class Item {
final String id;
final String name;
final String desc;
final num price;
final String color;
final String image;
Item(
{required this.id,
required this.name,
required this.desc,
required this.price,
required this.color,
required this.image});
factory Item.fromMap(Map<String, dynamic> map) {
return Item(
id: map["id"] as String,
name: map["name"] as String,
desc: map["desc"] as String,
price: map["price"] as int,
color: map["color"] as String,
image: map["image"] as String,
);
}
toMap() => {
"id": id,
"name": name,
"desc": desc,
"price": price,
"color": color,
"image": image,
};
}
获取 JSON 数据的函数。
loadData() async {
var catalogJson = await rootBundle.loadString("assets/files/catalog.Json");
final decodeData = jsonDecode(catalogJson);
var productData = decodeData["products"];
CatalogModel.items = List.from(productData);
CatalogModel.items =
List.from(productData).map<Item>((item) => Item.fromMap(item)).toList();
setState(() {});
}
【问题讨论】:
-
你应该删除
CatalogModel.items = List.from(productData);这一行