Home > Blockchain >  Flutter: how to post array data in post api
Flutter: how to post array data in post api

Time:11-23

I want to post servieces data and packages data in post type api. But I dont know how to send multiple services and multiple packages data in this type of 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"
}

I send data in post api in flutter code like this


                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 
                };

CodePudding user response:

You can make model classes and write toJson inside models to do this task :

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;
  }
}

these classes can be your models and you should use Data class like this:

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();

and for packages do like services.

CodePudding user response:

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,
  };
}

First create send data model.

  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);

if you want to send it via formData.

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

CodePudding user response:

First of all, you need to create model class for those json object.

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,
    };
}

For Api call, you get string bookingStringDataForApi:

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

And then post bookingStringDataForApi using formdata

  • Related