首页 > 解决方案 > 如何在飞镖中访问子类的变量

问题描述

我有一个名为 的类Invoices,该类包含一个类列表List<MenuInInvoice> menus。该类有两个名为和的MenuInInvoice变量。foodNameprice

但是在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来访问类的变量。

我怎样才能做到这一点?提前致谢!

标签: flutterdart

解决方案


我不确定您要达到的目标。

构造Invoice函数有五个命名参数,其中一个称为menus. 调用构造函数时,通过在前面写入参数名称和冒号来传递命名参数的参数。

在您的主要代码中:

Invoices invoices = new Invoices(
  tableNo: "01",
  orderNo: "001",
  customerName: "Jonh",
  orderDate: DateTime.now(),
  menus.foodName: "abc"
)

您正确地将参数传递给命名参数tableNoorderNo和。customerNameorderDate

但是语法menus.foodname: "abc"无效。没有参数 named menus.foodName,它甚至不是一个有效的名称(单个标识符)。

您能否描述您期望/希望代码执行的操作,因为从您提供的代码中并不清楚。


推荐阅读