0

我有一个 StyleItem 类,如下所示:

class StyleItem {
  String id;
  double dx;
  double dy;
  double scale;
  double rotation;

  StyleItem({this.id, this.dx, this.dy, this.scale, this.rotation});

  Map toJson() {
    return {
      'id': id,
      'dx': dx,
      'dy': dy,
      'scale': scale,
      'rotation': rotation,
    };
  }

  @override
  String toString() {
    return 'id: $id, dx: $dx, dy: $dy, scale: $scale';
  }
}

然后我有一个补丁请求,它的主体应该看起来像

{
    "occasion": "[Date, Outing, Ethnic]",
    "weather": "[Rainy, Sunny]",
    "style_items": [
        {"id": "5faacbb3ac0d1900177e94bd", "dx": "0.35462962962962963", "dy": "0.7447916666666667", "scale": "0.4", "rotation": "0.0"}
    ]
}

该字段style_items应该具有类对象的此类映射的数组StyleItem。我试过用 编码这些对象jsonEncode,但后端无法读取id

通过 Postman,我确保后端工作正常。

为了发出我正在使用的补丁请求,请http打包。使用以下代码

// This is the complete function
// First I upload a picture for which I get a 'imgUrl'
// With this and other information, I make the patch request
// Field 'style_items' is the one which causes problem.
Future<bool> addNewLook(var image, Map<String, String> details, List<StyleItem> styleItems) async {
    try {
      Uri savingImgUrl = Uri.http(BASE_URL, CHAT_IMAGE_URL);
      var request = http.MultipartRequest('POST', savingImgUrl);
      request.files
          .add(await http.MultipartFile.fromPath('image', image.path));
      request.headers.addAll({'token': token});
      var res = await request.send();
      var response = await http.Response.fromStream(res);
      var resBody = jsonDecode(response.body);
      String imgUrl = resBody['url'];
      print("ImgUrl: "+imgUrl);

      // Required section, where I face the issue.
      Uri savingDataUrl = Uri.http(BASE_URL, CREATE_LOOK+"/$_id");
      var body = {
        'image': imgUrl,
        'occasion': details['occasion'],
        'weather': details['weather'],
        // This field has the problem
        'style_items': jsonEncode(styleItems.map((e) => e.toJson()).toList())
      };
      response = await http.patch(savingDataUrl, headers: {
        'token': token
      }, body: body);
      if(response.statusCode!=200) {print("ErrorAddingNewLook! Response: "+response.body); return false;}
      print(response.body);
      resBody = jsonDecode(response.body);
      Look look = Look();
      look.fromJson(resBody['data']);
      _request.preMadeLooks.add(look);
      print("SavingLooks: Response: "+resBody.toString());
      return true;
    } catch(err) {
      print("ErrorAddingNewLook! Error: "+err.toString());
      return false;
    }
  }

我还尝试以style_items不同的方式为该字段编码为 Json

// Try1
styleItems.map((e) => jsonEncode(e.toJson())).toList()
// Try2
styleItems.map((e) => jsonEncode(e.toJson())).toList().toString()
// Try3
jsonEncode(styleItems.map((e) => jsonEncode(e.toJson())).toList())
4

0 回答 0