3

My using package http

I have this method in my app to send post request with files. In my case I send files and also fields with dynamic values. I tried send List<String> but server (backend) return me error with message:

The seedlings field must be an array.

Example seedlings list value:

List<String> seedlings = ['Apple', 'Banana'];

Code:

Future post(String path, data) async {
  await _getToken();

  var url = '${ApiConstants.BASE_URL}$path';
  var uri = Uri.parse(url);
  var request = MultipartRequest('POST', uri);

  data.forEach((key, item) async {
    if (item == null) return null;
    if (item is File) {
      request.files.add(await MultipartFile.fromPath(
        'file',
        item.path,
      ));
    } else {
      request.fields[key] = item is num
        ? item.toString()
        : item is List
            ? item.toString()
            : item;
    }
  });

  request.headers['Content-type'] = 'application/json';
  request.headers['Accept'] = 'application/json';

  var response = await request.send();
}

In my case all fields sent to server except fields with list of values like array

1
  • You have to use a for loop and assign indexes for list Commented Jan 10, 2021 at 13:28

2 Answers 2

2

I have found an answer for this which I have posted in another similar question. I'll just put the code snippet here.

final request = http.MultipartRequest('Post', uri);
List<String> ManageTagModel = ['xx', 'yy', 'zz'];
for (String item in ManageTagModel) {
    request.files.add(http.MultipartFile.fromString('manage_tag_model', item));
}

Basically you have to add the list as files with fromString() method. Find the original answer here- https://stackoverflow.com/a/66318541/7337717

Sign up to request clarification or add additional context in comments.

1 Comment

This looks weird, but it works
2

This might be old, but you can easily do this by adding the array items into a form data array

final FormData formData = FormData({});

// Add all normal string request body data
formData.fields.add(MapEntry("name", "Olayemii"));    
formData.fields.add(MapEntry("age", 99));   

// Add all files request body data
formData.files.add(MapEntry("profile_photo", file));


// Add the array item 
List<String> seedlings = ['Apple', 'Banana'];

seedlings.forEach((element) {
    formData.fields.add(MapEntry("seedlings[]", element.toString()));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.