如何在 flutter 中发送多部分请求中的对象列表?

How to send List of objects in a multipart request in flutter?

我想在多部分请求中发送 ManageTagModel 列表以及其他模型和文件..

我不确定如何发送这个模型列表..

这是我发送不带列表的多部分请求的代码:

   var uri = Uri.parse(...);
    final request = http.MultipartRequest('Post', uri);
    request.fields['Id'] = '3';
    request.fields['Name'] = siteModel.name;
    request.fields['MapAddress'] = siteModel.mapAddress;
    request.fields['Country'] = siteModel.country;
    request.fields['City'] = siteModel.city;
    request.fields['CategoryNb'] = siteModel.categoryNb;
    request.fields['UserId'] = userId;
    request.fields['Caption'] = caption;
    for (File i in
    multipleFiles) {

      final mimeTypeData =
      lookupMimeType(i.path, headerBytes: [0xFF, 0xD8]).split('/');
      print("IMAGE: " + i.path);
      // Attach the file in the request
      final file = await http.MultipartFile.fromPath('files', i.path);
      print(mimeTypeData[0] + " mimeTypeData[0]");
      print(mimeTypeData[1] + " mimeTypeData[1]");

      request.files.add(file);

这是我的模型:

  import 'dart:convert';

   class ManageTagModel {
   String posX;
 String posY;
 String postOrder;
 String tagger;
 String tagged;

  ManageTagModel(
  {this.posX, this.posY, this.postOrder, this.tagger, this.tagged});

  //Flutter way of creating a constructor
  factory ManageTagModel.fromJson(Map<String, dynamic> json) => ManageTagModel(
  posX: json['PosX'],
  posY: json['PosY'],
  postOrder: json['PostOrder'],
  tagged: json['Tagged'],
  tagger: json['Tagger']);
  Map<String, dynamic> toMap() {
return {
  "PosX": posX,
  "PosY": posY,
  "PostOrder": postOrder,
  "Tagger": tagger,
  "Tagged": tagged
};
}
}

   List<ManageTagModel> fromJson(String jsonData) {
 // Decode json to extract a map
  final data = json.decode(jsonData);
  return List<ManageTagModel>.from(
  data.map((item) => ManageTagModel.fromJson(item)));
   } 

 String toJson(ManageTagModel data) {
 // First we convert the object to a map
 final jsonData = data.toMap();
  // Then we encode the map as a JSON string
 return json.encode(jsonData);
 }

 List encodeToJson(List<ManageTagModel> list) {
 List jsonList = List();
 list.map((item) => jsonList.add(item.toMap())).toList();
 return jsonList;
 }

我的后端 c# 方法有一个参数 List

感谢任何帮助!!

我很确定我来晚了,您可能已经找到了解决方案。我经历了多个线程,实际上并没有找到任何答案,但我发现自己是出于沮丧,并心想对于任何其他迷失的人类灵魂来说,答案实际上仍然不存在。所以这是我的解决方案,适用于仍然卡在这里的任何人,这非常直观。

您只需将列表的所有元素作为“文件”而不是“字段”添加到请求中。但是您必须使用 fromString().

而不是 fromPath() 方法
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));
}

这对我有用,我希望对你也有用。

如果数据不是字符串

for (int item in _userData['roles']) {
    request.files
        .add(http.MultipartFile.fromString('roles', item.toString()));
  }