Home > Mobile >  Array in POST form data in Flutter
Array in POST form data in Flutter

Time:09-17

I've prepared a request on postman that updates an array of data on my website and copied the dart code to my flutter app, here is the postman code

var headers = {
  'Authorization': '...',
  'Cookie': '...'
};
var request = http.MultipartRequest('POST', Uri.parse('my_endpoint'));
request.fields.addAll({
  'fields[0][field_id]': '20',
  'fields[0][group_id]': '1',
  'fields[0][value][]': 'Android Developer',
  'fields[0][value][]': 'Web Developer'
});

request.headers.addAll(headers);

http.StreamedResponse response = await request.send();

if (response.statusCode == 200) {
  print(await response.stream.bytesToString());
}
else {
  print(response.reasonPhrase);
}

the problem is that Flutter removes the last pair in the body map because it has the same key as the previous one, so only the result of the update operation is Web Developer only, but I think my request only works this way, how can I deal with this issue.

CodePudding user response:

You can send an array in formData as {key[value][0]: value1, key[value][1]: value2, ...}. A way to achieve that here would be:

final values = ["Android Developer", "Web Developer"];
Map<String, String> valuesArray = {
  for (var i = 0; i < values.length; i  ) 'fields[0][value][$i]': values[i]
};
request.fields.addAll({
  ...valuesArray,
  'fields[0][field_id]': '20',
  'fields[0][group_id]': '1',
});

Alternatively, if possible, I would advise you to use a content-type:json as it's easier to just create a Map<String, dynamic> body and encoding it using jsonEncode.

  • Related