【问题标题】:Flutter: how to post array data in post apiFlutter:如何在 post api 中发布数组数据
【发布时间】:2022-01-01 16:13:04
【问题描述】:

我想在发布类型 api 中发布服务数据和打包数据。 但是我不知道如何在这种类型的json中发送多个服务和多个包数据。

{
    "branch_uuid": "2e62af28-3a9e-4309-bff4-66e74a322c5x",
    "date": "2021-09-17",
    "time": "11:00",
    "services": [
        {
            "uuid": "63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420",
            "staff_uuid": "e29b9e3a-0d28-472a-ae27-c372b4ca1a89"
        },
        {
            "uuid": "674d978a-0d88-4374-b915-9c42630f6aa7",
            "staff_uuid": "3a211faf-938b-4220-8288-dfe860ed3b13"
        }
    ],
    "packages": [
        {
            "uuid": "ba88f33f-9a48-4cf1-b55c-45ccce6e7253",
            "services": [
                {
                    "uuid": "63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420"
                },
                {
                    "uuid": "674d978a-0d88-4374-b915-9c42630f6aa7"
                }
            ]
        },
        {
            "uuid": "4de60d34-526b-4ac2-9df4-34876f58e39d",
            "services": [
                {
                    "uuid": "674d978a-0d88-4374-b915-9c42630f6aa7"
                }
            ]
        }
    ],
    "remarks": "",
    "tax": 100,
    "discount": 400,
    "coupon": "SALE100"
}

我用这样的颤振代码在 post api 中发送数据


                var bookingData = {

               "branch_uuid": widget.branchListData['uuid'].toString(), 
              "date":"${widget.selectedDate}-${widget.selectedMonthInNum}-${widget.selectedYear}",
                  "time": "${widget.choosedTime}"
                  "services": // what and how to do here,
                  "packages": // what and how to do here 
                };

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies flutter-test


    【解决方案1】:

    您可以制作模型类并在模型中写入 toJson 来完成此任务:

    class Data {
      String branchUuid;
      String date;
      String time;
      List<Services> services;
      List<Packages> packages;
      String remarks;
      int tax;
      int discount;
      String coupon;
    
      Data(
          {this.branchUuid,
          this.date,
          this.time,
          this.services,
          this.packages,
          this.remarks,
          this.tax,
          this.discount,
          this.coupon});
    
      Data.fromJson(Map<String, dynamic> json) {
        branchUuid = json['branch_uuid'];
        date = json['date'];
        time = json['time'];
        if (json['services'] != null) {
          services = new List<Services>();
          json['services'].forEach((v) {
            services.add(new Services.fromJson(v));
          });
        }
        if (json['packages'] != null) {
          packages = new List<Packages>();
          json['packages'].forEach((v) {
            packages.add(new Packages.fromJson(v));
          });
        }
        remarks = json['remarks'];
        tax = json['tax'];
        discount = json['discount'];
        coupon = json['coupon'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['branch_uuid'] = this.branchUuid;
        data['date'] = this.date;
        data['time'] = this.time;
        if (this.services != null) {
          data['services'] = this.services.map((v) => v.toJson()).toList();
        }
        if (this.packages != null) {
          data['packages'] = this.packages.map((v) => v.toJson()).toList();
        }
        data['remarks'] = this.remarks;
        data['tax'] = this.tax;
        data['discount'] = this.discount;
        data['coupon'] = this.coupon;
        return data;
      }
    }
    
    class Services {
      String uuid;
      String staffUuid;
    
      Services({this.uuid, this.staffUuid});
    
      Services.fromJson(Map<String, dynamic> json) {
        uuid = json['uuid'];
        staffUuid = json['staff_uuid'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['uuid'] = this.uuid;
        data['staff_uuid'] = this.staffUuid;
        return data;
      }
    }
    
    class Packages {
      String uuid;
      List<Services> services;
    
      Packages({this.uuid, this.services});
    
      Packages.fromJson(Map<String, dynamic> json) {
        uuid = json['uuid'];
        if (json['services'] != null) {
          services = new List<Services>();
          json['services'].forEach((v) {
            services.add(new Services.fromJson(v));
          });
        }
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['uuid'] = this.uuid;
        if (this.services != null) {
          data['services'] = this.services.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }
    
    class Services {
      String uuid;
    
      Services({this.uuid});
    
      Services.fromJson(Map<String, dynamic> json) {
        uuid = json['uuid'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['uuid'] = this.uuid;
        return data;
      }
    }
    

    这些类可以是你的模型,你应该像这样使用 Data 类:

    List<Services> services = [Service(uuid:"63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420",staff_uuid :"3a211faf-938b-4220-8288-dfe860ed3b13"),Service(uuid:"674d978a-0d88-4374-b915-9c42630f6aa7",staff_uuid : "3a211faf-938b-4220-8288-dfe860ed3b13"), ];
    
    List<Packages> packages = [Packages(uuid : "ba88f33f-9a48-4cf1-b55c-45ccce6e7253",[Service(uuid:"63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420",staff_uuid :"3a211faf-938b-4220-8288-dfe860ed3b13")]),Packages(uuid : "ba88f33f-9a48-4cf1-b55c-45ccce6e7253",[Service(uuid:"63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420",staff_uuid :"3a211faf-938b-4220-8288-dfe860ed3b13")]), ];
    
        Map<String, dynamic> map = Data(
        branch_uuid : widget.branchListData['uuid'].toString(),
        date : "${widget.selectedDate}-${widget.selectedMonthInNum}-${widget.selectedYear}",
        time: "${widget.choosedTime}",
        services : services,
        packages : packages,
        ).toJson();
    

    对于包确实喜欢服务。

    【讨论】:

    • 但是我的服务可以是多个而不是两个或一个然后如何发送,以及包裹如何发送它们
    • 没有什么不同,您可以创建服务列表并将其传递给 Data 构造函数
    • 我编辑了我的答案以便更容易理解。
    【解决方案2】:
    import 'dart:convert';
    
    SendDataModel sendDataModelFromJson(String str) => SendDataModel.fromJson(json.decode(str));
    
    String sendDataModelToJson(SendDataModel data) => json.encode(data.toJson());
    
    class SendDataModel {
      SendDataModel({
        this.branchUuid,
        this.date,
        this.time,
        this.services,
        this.packages,
        this.remarks,
        this.tax,
        this.discount,
        this.coupon,
      });
    
      String? branchUuid;
      String? date;
      String? time;
      List<SendDataModelService>? services;
      List<Package>? packages;
      String? remarks;
      int? tax;
      int? discount;
      String? coupon;
    
      factory SendDataModel.fromJson(Map<String, dynamic> json) => SendDataModel(
        branchUuid: json["branch_uuid"] == null ? null : json["branch_uuid"],
        date: json["date"] == null ? null : json["date"],
        time: json["time"] == null ? null : json["time"],
        services: json["services"] == null ? null : List<SendDataModelService>.from(json["services"].map((x) => SendDataModelService.fromJson(x))),
        packages: json["packages"] == null ? null : List<Package>.from(json["packages"].map((x) => Package.fromJson(x))),
        remarks: json["remarks"] == null ? null : json["remarks"],
        tax: json["tax"] == null ? null : json["tax"],
        discount: json["discount"] == null ? null : json["discount"],
        coupon: json["coupon"] == null ? null : json["coupon"],
      );
    
      Map<String, dynamic> toJson() => {
        "branch_uuid": branchUuid == null ? null : branchUuid,
        "date": date == null ? null : date,
        "time": time == null ? null : time,
        "services": services == null ? null : List<dynamic>.from(services!.map((x) => x.toJson())),
        "packages": packages == null ? null : List<dynamic>.from(packages!.map((x) => x.toJson())),
        "remarks": remarks == null ? null : remarks,
        "tax": tax == null ? null : tax,
        "discount": discount == null ? null : discount,
        "coupon": coupon == null ? null : coupon,
      };
    }
    
    class Package {
      Package({
        this.uuid,
        this.services,
      });
    
      String? uuid;
      List<PackageService>? services;
    
      factory Package.fromJson(Map<String, dynamic> json) => Package(
        uuid: json["uuid"] == null ? null : json["uuid"],
        services: json["services"] == null ? null : List<PackageService>.from(json["services"].map((x) => PackageService.fromJson(x))),
      );
    
      Map<String, dynamic> toJson() => {
        "uuid": uuid == null ? null : uuid,
        "services": services == null ? null : List<dynamic>.from(services!.map((x) => x.toJson())),
      };
    }
    
    class PackageService {
      PackageService({
        this.uuid,
      });
    
      String? uuid;
    
      factory PackageService.fromJson(Map<String, dynamic> json) => PackageService(
        uuid: json["uuid"] == null ? null : json["uuid"],
      );
    
      Map<String, dynamic> toJson() => {
        "uuid": uuid == null ? null : uuid,
      };
    }
    
    class SendDataModelService {
      SendDataModelService({
        this.uuid,
        this.staffUuid,
      });
    
      String? uuid;
      String? staffUuid;
    
      factory SendDataModelService.fromJson(Map<String, dynamic> json) => SendDataModelService(
        uuid: json["uuid"] == null ? null : json["uuid"],
        staffUuid: json["staff_uuid"] == null ? null : json["staff_uuid"],
      );
    
      Map<String, dynamic> toJson() => {
        "uuid": uuid == null ? null : uuid,
        "staff_uuid": staffUuid == null ? null : staffUuid,
      };
    }
    

    首先创建发送数据模型。

      late SendDataModel data;
    
      data = SendDataModel(
        branchUuid: "branchUuid",
        coupon: "coupon",
        date: "date",
        time: "time",
        discount: 12345,
        remarks: "remarks",
        tax: 12345,
      );
    
      List<SendDataModelService>? sendDataModelServiceList = [];
    
      // If you have an expandable list
      // If you keep the data as List<SendDataModelService> while keeping the data initially, you can make data.service = yourList without the need for ".add".
    
      sendDataModelServiceList.add(SendDataModelService(uuid: "uuid", staffUuid: "staffUuid"));
      data.services = sendDataModelServiceList;
    
      List<Package> sendDataModelPackageList = [];
      List<PackageService> tmpPackageServiceList = [];
      tmpPackageServiceList.add(PackageService(uuid: "uuid"));
      sendDataModelPackageList.add(Package(uuid: "uuid", services: tmpPackageServiceList));
    
      // The important thing here is to keep your data in the model type that was created when you first created it, so your data will not be mixed.
    
      var encodedData = jsonEncode(data);
    

    如果你想通过 formData 发送。

       formData: FormData.fromMap({
            "formDataKey": jsonEncode({
              data,
            }),
          }),
    

    【讨论】:

      【解决方案3】:

      首先,你需要为那些json对象创建模型类。

      import 'dart:convert';
      
      
      BookingData bookingDataFromJson(String str) => BookingData.fromJson(json.decode(str));
      
      String bookingDataToJson(BookingData data) => json.encode(data.toJson());
      
      class BookingData {
          BookingData({
              this.branchUuid,
              this.date,
              this.time,
              this.services,
              this.packages,
              this.remarks,
              this.tax,
              this.discount,
              this.coupon,
          });
      
          String branchUuid;
          DateTime date;
          String time;
          List<BookingDataService> services;
          List<Package> packages;
          String remarks;
          int tax;
          int discount;
          String coupon;
      
          factory BookingData.fromJson(Map<String, dynamic> json) => BookingData(
              branchUuid: json["branch_uuid"],
              date: DateTime.parse(json["date"]),
              time: json["time"],
              services: List<BookingDataService>.from(json["services"].map((x) => BookingDataService.fromJson(x))),
              packages: List<Package>.from(json["packages"].map((x) => Package.fromJson(x))),
              remarks: json["remarks"],
              tax: json["tax"],
              discount: json["discount"],
              coupon: json["coupon"],
          );
      
          Map<String, dynamic> toJson() => {
              "branch_uuid": branchUuid,
              "date": "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
              "time": time,
              "services": List<dynamic>.from(services.map((x) => x.toJson())),
              "packages": List<dynamic>.from(packages.map((x) => x.toJson())),
              "remarks": remarks,
              "tax": tax,
              "discount": discount,
              "coupon": coupon,
          };
      }
      
      class Package {
          Package({
              this.uuid,
              this.services,
          });
      
          String uuid;
          List<PackageService> services;
      
          factory Package.fromJson(Map<String, dynamic> json) => Package(
              uuid: json["uuid"],
              services: List<PackageService>.from(json["services"].map((x) => PackageService.fromJson(x))),
          );
      
          Map<String, dynamic> toJson() => {
              "uuid": uuid,
              "services": List<dynamic>.from(services.map((x) => x.toJson())),
          };
      }
      
      class PackageService {
          PackageService({
              this.uuid,
          });
      
          String uuid;
      
          factory PackageService.fromJson(Map<String, dynamic> json) => PackageService(
              uuid: json["uuid"],
          );
      
          Map<String, dynamic> toJson() => {
              "uuid": uuid,
          };
      }
      
      class BookingDataService {
          BookingDataService({
              this.uuid,
              this.staffUuid,
          });
      
          String uuid;
          String staffUuid;
      
          factory BookingDataService.fromJson(Map<String, dynamic> json) => BookingDataService(
              uuid: json["uuid"],
              staffUuid: json["staff_uuid"],
          );
      
          Map<String, dynamic> toJson() => {
              "uuid": uuid,
              "staff_uuid": staffUuid,
          };
      }
      

      对于 Api 调用,您会得到字符串 bookingStringDataForApi:

      String bookingStringDataForApi = bookingDataToJson(/*TODO pass booking model object*/)
      

      然后使用 formdata 发布 bookingStringDataForApi

      【讨论】:

        猜你喜欢
        • 2022-01-04
        • 1970-01-01
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 2020-10-24
        • 1970-01-01
        • 1970-01-01
        • 2014-12-24
        相关资源
        最近更新 更多