Flutter Dio post an object with array
Asked Answered
L

2

11

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.

Landpoor answered 1/5, 2020 at 12:49 Comment(0)
S
32

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),
);
Samos answered 1/5, 2020 at 13:12 Comment(6)
thanks for the hint, it actually worked. I thought sending params as an object is enough but as i tried sending authentication params to the same api. ThanksLandpoor
cant we send this type of array in get method?Cinquecento
GET requests don't have a body and the data has to be put in URL parameters. In general that can be tricky, but it's definitely possible. The first code snippet suggests a way of using GET, the second snippet is for using POST which would generally be the better option but you need to change this on server side as wellSamos
good example...Moor
Hi there, I tried this sample code in dio^4.0.6, but I couldn't receive data in my server. Other way I tried @AmirahmadAdibi 's answer and it works. Is this caused by dio version?Burgett
That would be rather unlikely. I assume your API might be expecting form data instead of jsonSamos
E
0

another example for any one might be helpful , posting fomr data

            var formData = FormData.fromMap({
              'data': json.encode(
                  {'salt': salt, 'placeholder': 'palceholder', 
                  'method_name': 'app_details'})
            });

            var response = await dio.post(
              BaseUrl,
              data: formData,
            );

the final result of your request is this

enter image description here

Ewald answered 3/7, 2022 at 8:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.