Flutter Dio post an object with array

Mujtaba Mahmood picture Mujtaba Mahmood · May 1, 2020 · Viewed 14.7k times · Source

I am trying to post a request to api with an object as"

var params =  {
    "item": "itemx",
    "options": [1,2,3],
    };
    print(params);
    try {
      Response response = await _dio.post(getAddToCartURL,
          queryParameters: params,
          options: Options(headers: {
            HttpHeaders.contentTypeHeader: "application/json",
          }));

    } catch (error, stackTrace) {
      print("Exception occurred: $error  stackTrace: $stackTrace");
      return false;
    }

Dio sends the object as :

POST /api/add-to-cart/?item=itemx&options%5B%5D=1&options%5B%5D=2&options%5B%5D=3 

in which the api recognize it as a bad request.

what is wrong that i am doing here? I have even tried the list as [ "1","2","3"], it is the same.

Answer

dumazy picture dumazy · May 1, 2020

It all depends on how the API expects it. I would suggest trying to encode it as JSON.

var params =  {
  "item": "itemx",
  "options": jsonEncode([1,2,3]),
};

But sending complex data in query parameters isn't always that easy. Since you are using POST anyway, maybe send a JSON object as body instead of using query parameters.

var params =  {
  "item": "itemx",
  "options": [1,2,3],
}; 
...
Response response = await _dio.post(getAddToCartURL,
  options: Options(headers: {
    HttpHeaders.contentTypeHeader: "application/json",
  }),
  data: jsonEncode(params),
);