Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Dio post an object with array

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.

like image 418
Mujtaba Mahmood Avatar asked May 01 '20 12:05

Mujtaba Mahmood


2 Answers

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),
);
like image 93
dumazy Avatar answered Oct 18 '22 19:10

dumazy


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

like image 1
AmirahmadAdibi Avatar answered Oct 18 '22 21:10

AmirahmadAdibi