1:使用类中的属性作为模板,实例化时接收参数,然后返回一个dart 中的Map类ing数据
2:接收的参数是什么格式?
直接一一对应dart类型–使用普通构造函数
接收的是一个Map类型数据,那么就需要提取Map中的value,需要定义命名构造函数
3:类中定义方法 用来输出一个Map类型数据
class Shangpin {
String? goodId;
int? amount;
String? goodImage;
double? goodPrice;
String? goodName;
Shangpin(this.goodId, this.amount, this.goodImage, this.goodPrice, this.goodName);
Shangpin.fromJson(Map<String, dynamic> json) {
goodId = json['goodId'];
amount = json['amount'];
goodImage = json['goodImage'];
goodPrice = json['goodPrice'];
goodName = json['goodName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['goodId'] = this.goodId;
data['amount'] = this.amount;
data['goodImage'] = this.goodImage;
data['goodPrice'] = this.goodPrice;
data['goodName'] = this.goodName;
return data;
}
}
void main() {
//s1实例和s2实例
Shangpin s1 = Shangpin('000001', 999, 'http://192.168.2.168/images/1.png', 80.00, '商品1名称');
Shangpin s2 = Shangpin.fromJson({'goodId': '000002','amount': 666,'goodImage': 'http://192.168.2.168/images/2.png','goodPrice': 688.00,'goodName': '商品2名称'});
print(s1); //实例
print(s2); //实例
var a = s1.toJson();//a=={goodId: 000001, amount: 999, goodImage: http://192.168.2.168/images/1.png, goodPrice: 80.0, goodName: 商品1名称}
var b = s2.toJson();//b=={goodId: 000002, amount: 666, goodImage: http://192.168.2.168/images/2.png, goodPrice: 688.0, goodName: 商品2名称}
}
版权声明:本文为weixin_47021806原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。