gpt4 book ai didi

dart - 如何从JSON创建上级和子类?

转载 作者:行者123 更新时间:2023-12-03 04:13:27 24 4
gpt4 key购买 nike

我一直在尝试找出如何使用命名构造函数从JSON构造父类和子类。以下是我的示例,并提供了一些关于fromJson方法主体中尝试过的内容的注释。谁能指出我正确的方向?谢谢!

class Item {
final String name;
final int id;
final String image;
final double price;
final bool available;

Item(this.name, this.id, this.image, this.price, this.available);

Item.fromJson(Map<String, dynamic> json)
: name = json['name'],
id = json['id'],
image = json['image'],
price = json['price'],
available = json['available'];

}

class CartItem extends Item {
final int quantity;

CartItem({
@required this.quantity,
@required name,
@required id,
@required price,
@required image,
@required available

}): super(id, name, image, price, available)

CartItem.fromJson(Map<String, dynamic> json)
: quantity = json['quantity'],
// for whatever ever reason, super here seems to refer to CartItem
// so this doesn't work
super.name = json['name'],
// calling 'name' without the super doesn't work either
name = json['name']
}

最佳答案

您应该在子类的super构造函数中使用fromJsonfromJson构造函数。您可以将子级中的Map直接传递给super,而不会出现问题。例如:

CartItem.fromJson(Map<String, dynamic> json) 
: quantity = json['quantity'],
super.fromJson(json);

关于dart - 如何从JSON创建上级和子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62918182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com