Jayrek
Jayrek

Reputation: 53

Flutter HTTP post request sending list of objects

I have successfully got a 200 response code from the server but my API returns response code of 0. When I try to send a request in the postman it response to 1. Maybe I do have something missing in my JSON to send in the body. I'm new to flutter and I would like to send a post HTTP request with a body of list of objects like below: I really appreciate any help.


    [
        {
            "product_id": 14,
            "quantity": 3,
            "payment": "COD"
        },
        {
            "product_id": 3,
            "quantity": 2,
            "payment": "COD"
        }
    ]

This is my function for HTTP post:

Future<dynamic> checkItem({Map headers, body, encoding}) async {
    Map<String, String> headers = {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $token'
    };
    try {
      final response = await http.post(
          '${_url}transactions/check',
          headers: headers,
          body: body,
          encoding: Encoding.getByName("utf-8"));
      if (response.statusCode == 200) {
        String data = response.body;
        return jsonDecode(data);
      } else {
        print(response.statusCode);
      }
    } catch (error) {
      print(error);
    }
  }

This is how I call the function which I pass my JSON:

 List<String> chckList = checkoutList.map((e) => json.encode(e.toJson())).toList();
 String strBody = json.encode(chckList);
 final res = await interface.checkOutItem(body: strBody);

This is my toJson in my Model object:


 Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['product_id'] = this.product_id;
    data['quantity'] = this.quantity;
    data['payment'] = this.payment;
    return data;
  }

Upvotes: 0

Views: 4871

Answers (1)

Omatt
Omatt

Reputation: 10473

The request in your code seems to all line in place. The issue likely lies on the API you're using that's unable to handle to handle the payload that you're sending.

Upvotes: 0

Related Questions