How to send array in a formdata in Flutter using Dio package?

Viewed 3452

I want to send a File with a complex JSON object containing JSON Array. How can I do it? enter image description here

I want to send this kind of FormData. Here is how I have implemented it:

final data = {
  "id": 60,
  "first_name": "Amit",
  "last_name": "Sharma",
  "email": "j.purohit198@gmail.com",
  "phone_no": "1111111111",
  "addr": "Lko",
  "status": "VERIFIED",
  "total_funds": 0,
  "bankDetails": [
    {"name": "ASD", "acc": "123"},
    {"name": "ASDFG", "acc": "1234"}
  ]
};
if (file != null) {
  data['pic'] =
      MultipartFile.fromFileSync(file.path, filename: 'profile_image');
}
final formData = FormData.fromMap(data);

final formData = FormData.fromMap(data);

final res = await _dio
    .post(
      '$kBaseUrl$kUploadPlanterStory',
      options: Options(
        headers: headers,
        contentType: Headers.formUrlEncodedContentType,
      ),
      data: formData,
    )
    .catchError((e) => throw getFailure(e));

print(res);

}

4 Answers

Currently you are using urlEncoded to encode whole data map, which isn't what you want. If you want to encode a specific part of request using a different serialization method, you have to do it manually:


final data = {
  // urlEncoded fields
  // ...
  "bankDetails": jsonEncode([
    {"name": "ASD", "acc": "123"},
  ]),
};

//...
data: FormData.fromMap(data)

Remember to add "[]" after the key. Simplest Method to send array in form data :

FormData formData = new FormData.fromMap({
  "name": "Max",
  "location": "Paris",
  "age": 21,
  "image[]": [1,2,3],
});

Response response = await dio.post(
  //"/upload",
  "http://143.110.244.110/radius/frontuser/eventsubmitbutton",
  data: formData,
  onSendProgress: (received, total) {
    if (total != -1) {
      print((received / total * 100).toStringAsFixed(0) + '%');
    }
  },
);

https://github.com/flutterchina/dio/issues/1155#issuecomment-842492719

Another method would be using the ListFormat.multiCompatible param in FormData.

And I believe this will work on nested arrays without changing the structure of your body, encoding or adding [] to the keys: e.g.

FormData.fromMap(data, ListFormat.multiCompatible); // <-- add this
final dio = Dio();
dio.options.headers = {
  'Accept': 'application/json',
  'Content-Type': 'multipart/form-data',      
  };

FormData formData = new FormData();
formData = FormData.fromMap({
"[bankDetails][]": [ {"name": "ASD", "acc": "123"},
{"name": "ASDFG", "acc": "1234"} ] });
final responseJson = await dio.post(
    
    url,
    data: formData,
  );
Related