![](/img/trans.png)
[英]type 'Null' is not a subtype of type 'Map<String, dynamic>' flutter error
[英]type 'null' is not a subtype of type 'map string dynamic ' flutter
我正在嘗試在我的應用程序中使用 API 它可以正常工作,但是當 JSON 獲取 null 時,該應用程序無法正常工作。
正常工作:
{
"product":{
"description_1":"Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"description_2":"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.",
"description_3":"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteratenter code hereion in some form",
"description_4":"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested.",
"description_5":"Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like"
}
}
錯誤:“類型‘null’不是‘映射字符串動態’類型的子類型”:
{ “產品”:null }
Class:
class Store {
Store({
required this.product,
});
Product product;
factory Store.fromJson(Map<String, dynamic> json) => Store(
product: Product.fromJson(json["product"]),
);
Map<String, dynamic> toJson() => {
"product": product.toJson(),
};
}
class Product {
Product({
required this.description1,
required this.description2,
required this.description3,
});
String description1;
String description2;
String description3;
factory Product.fromJson(Map<String, dynamic> json) => Product(
description1: json["description_1"] ?? "",
description2: json["description_2"] ?? "",
description3: json["description_3"] ?? "",
);
Map<String, dynamic> toJson() => {
"description_1": description1,
"description_2": description2,
"description_3": description3,
};
}
如果產品實際上可以是null
那么Store
需要處理它。 將Store
class product
屬性更改為可以為空?
像下面這樣的符號:
class Store {
Store({
this.product,
});
Product? product;
factory Store.fromJson(Map<String, dynamic> json) => Store(
product: json["product"] != null
? Product.fromJson(json["product"])
: null,
);
Map<String, dynamic> toJson() => {
"product": product?.toJson(),
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.