How to send a array in MultipartRequest in flutter?

Viewed 2074

this is i am testing my api using postman as array

enter image description here

but how can i send array using MultipartRequest

var uri = Uri.parse(Constants.BASEURL + Constants.KEYEORD_CREATE_TENANACY);
  Map<String, String> headers = {
    "Accept": "application/json",
    "Authorization": token
    };
   var request = new http.MultipartRequest("POST", uri);
   request.headers.addAll(headers);
   request.fields['property_usage'] = property_use;
   request.fields['unit_id'] = unitlist;               // here i want unit_id to array
   var response = await request.send();
   print("Tenancy Add Result: ${response.statusCode}");
    if (response.statusCode == 200) {
     print(response);
    }
4 Answers

'''

request.fields['unit_id[n]'] = "${arrUnitlist[n]}";

or

for(int i = 0; i < arrUnitlist; i++){
  request.fields['unit_id[$i]'] = '${arrUnitlist[i]}';
}

'''

works for me

it is possible just open Multipart defination and change final fields = <String,String> to final fields = <String,dynamic> or any other datatype you want.

You can add your array data of unit_id like this:

var request = new http.MultipartRequest("POST", uri);
request.headers.addAll(headers);
request.fields['property_usage'] = property_use;
request.fields['unit_id[0]'] = "unitlist1";
request.fields['unit_id[1]'] = "unitlist2";
request.fields['unit_id[2]'] = "unitlist3";
var response = await request.send();

It is not possible , request.fileds is a Map<String,String>, So you have to provide a String , not an array. Is there a specific reason that you are using a MultipartRequest ? It is used to send files to servers , if you are not doing that you can use simple http functions like put and I think that would be more relevant for you . Get more details from official docs for put and MultipartRequest.

Related