我有一个名为Invoices
的类,并且该类包含一个类List<MenuInInvoice> menus
的列表。类MenuInInvoice
有两个变量,分别为foodName
和price
。
但是在main()
类中,我无法访问这些变量。
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
Invoices invoicesFromJson(String str) =>
Invoices.fromJson(json.decode(str));
String invoicesToJson(Invoices data) => json.encode(data.toJson());
class Invoices {
String orderNo;
String tableNo;
String customerName;
DateTime orderDate;
List<MenuInInvoice> menus;
DocumentReference reference;
Invoices({
this.orderNo,
this.tableNo,
this.customerName,
this.orderDate,
this.menus,
});
Invoices.fromJson(Map json,{this.reference}){
orderNo = json["orderNo"] ?? "unknown";
tableNo = json["tableNo"] ?? "unknown";
customerName = json["customerName"] ?? "unknown";
orderDate = DateTime.parse(json["orderDate"]);
menus = new List<MenuInInvoice>.from(json["menus"].map((x) => MenuInInvoice.fromJson(x)));
}
Invoices.fromSnapshot(DocumentSnapshot snapshot):
this.fromJson(snapshot.data, reference: snapshot.reference);
Map<String, dynamic> toJson() => {
"orderNo": orderNo ?? "unknown",
"tableNo": tableNo ?? "unknown",
"customerName": customerName ?? "unknown",
"orderDate": "${orderDate.year.toString().padLeft(4, '0')}-${orderDate.month.toString().padLeft(2, '0')}-${orderDate.day.toString().padLeft(2, '0')}",
"menus": new List<dynamic>.from(menus.map((x) => x.toJson())),
};
}
class MenuInInvoice {
String foodName;
String price;
MenuInInvoice({
this.foodName,
this.price,
});
factory MenuInInvoice.fromJson(Map json) => new MenuInInvoice(
foodName: json["foodName"] ?? "unknown",
price: json["price"] ?? "unknown",
);
Map<String, dynamic> toJson() => {
"foodName": foodName ?? "unknown",
"price": price ?? "unknown",
};
}
这是我的main()类:
Invoices invoices = new Invoices(
tableNo: "01",
orderNo: "001",
customerName: "Jonh",
orderDate: DateTime.now(),
menus.foodName: "abc"
)
在main()
类中,我无法使用语句menus.foodName
来访问类的变量。
我该怎么做? 预先感谢!
答案 0 :(得分:0)
代替:
Invoices invoices = Invoices(
tableNo: orderItem.tableNo,
orderNo: orderItem.orderNo,
customerName: orderItem.customerName,
orderDate: DateTime.now(),
menus: orderItem.menus.foodName
)
尝试:
Invoices invoices = new Invoices(
tableNo: orderItem.tableNo,
orderNo: orderItem.orderNo,
customerName: orderItem.customerName,
orderDate: DateTime.now(),
menus: orderItem.menus.foodName
)
答案 1 :(得分:0)
我不确定您要达到什么目标。
Invoice
构造函数有五个命名参数,其中一个称为menus
。
调用构造函数时,可以通过在参数名称前面加上一个冒号来传递命名参数的参数。
在您的主要代码中:
Invoices invoices = new Invoices(
tableNo: "01",
orderNo: "001",
customerName: "Jonh",
orderDate: DateTime.now(),
menus.foodName: "abc"
)
您可以正确地将参数传递给命名参数tableNo
,orderNo
,customerName
和orderDate
。
但是语法menus.foodname: "abc"
无效。没有名为menus.foodName
的参数,它甚至不是有效的名称(单个标识符)。
由于您提供的代码尚不清楚,您能描述一下您期望/想要执行的代码吗?
答案 2 :(得分:0)
您确实无法直接访问foodName。
请尝试以下操作:
List<MenuInInvoice> menuList = List<MenuInInvoice>();
menuList.add(MenuInInvoice(foodName: 'abc'));
Invoices invoices = Invoices(
tableNo: '01',
orderNo: '001',
customerName: 'Jonh',
orderDate: DateTime.now(),
menus: menuList);