flutter - 如何在飞镖中访问子类的变量
问题描述
我有一个名为 的类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
来访问类的变量。
我怎样才能做到这一点?提前致谢!
解决方案
我不确定您要达到的目标。
构造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"
无效。没有参数 named menus.foodName
,它甚至不是一个有效的名称(单个标识符)。
您能否描述您期望/希望代码执行的操作,因为从您提供的代码中并不清楚。
推荐阅读
- angular - *ngFor 未在 Angular MatDialog 中注册
- javascript - 我的提交和编辑表单的 React 模态组件不会关闭?
- google-analytics - 一个网络 + 一个 GTM 但不同的 Google Analytics
- python - 将 pandas 数据帧中的数据组织到 ndarray 以在 gpu 上运行
- reactjs - 我的状态在减速器和消费组件之间变化
- java - Gradle:如何提升来自插件的传递依赖版本?
- angular - NG0200:为 ApplicationRef 检测到 DI 中的循环依赖性
- python - TypeError: __init__() 得到了一个意外的关键字参数“xfid”
- c# - 有没有聪明的方法来解析 xml 到列表?
- canvas - 如何将风玫瑰图嵌入 GUI