HTTP send list data to raw body as request in flutter

Viewed 1258

I am trying to call POST API which has raw body request parameters. Raw body also contains list data. I am also attaching postman request and my tried code. I am not getting success response. Please correct me if i have done something wrong

enter image description here

My code:

Future<SaveBookingModel> saveBookingModel(SaveBookingRequestModel saveBookingRequestModel, BuildContext context) async{

  String url = baseUrl + "booking/save";

  var body = {
    "customer_id": "2",
    "location_id": "1",
    "discount_amount": "20.00",
    "discount_voucher": "V123",
    "BookingItems": [{
      "court_id": "3",
      "from_time": "21/10/2021 7:00PM",
      "to_time": "21/10/2021 8:00PM ",
      "amount": "150.00",
      "hours": "1",
      "time_slot_from": "7",
      "time_slot_to": "8"
    },
      {
        "court_id": "3",
        "from_time": "21/10/2021 10:00PM",
        "to_time": "21/10/2021 11:00PM",
        "amount": "100.00",
        "hours": "1",
        "time_slot_from": "10",
        "time_slot_to": "11"
      }
    ],
    "BookingPayments": [{
      "paid_amount": "230.00",
      "payment_desc": "desc",
      "payment_status": "1",
      "payment_method": "8",
      "reference1": "reference1",
      "reference2": "reference2",
      "reference3": "reference3"
    }
    ]
  };
  print("Save booking request body ${saveBookingRequestModel.toJson()}");
  Utils.showLoaderDialog(context);
  final response = await http.post(Uri.parse(url), headers: {
  "Accept": "application/json",
  "Content-Type":"application/json",
    'Authorization':'Bearer ${Utils.token}',
  }, body: body
  );

  print("Save booking request response $saveBookingRequestModel");
  print("Save booking response response ${response.body}");
  if(response.statusCode == 200){
    Navigator.pop(context);

      return SaveBookingModel.fromJson(json.decode(response.body));


  }else {
    return Utils.errorDialog(context, "Something went wrong");
  }

}
1 Answers

From the docs of the post method you are using above:

If [body] is a Map, it's encoded as form fields using [encoding]. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.

But your content type is actually application/json. Thus you need to json encode the map for the request to succeed. import dart:convert and pass the map to the jsonEncode function.

Related