如何在flutter Dio包中发布formData中的对象?

hmmo2u0o  于 2022-12-30  发布在  Flutter
关注(0)|答案(3)|浏览(421)

我有一个包含modelHeight、modelWeight和modelSize对象的“modelCharacteristics”对象,如何将JSON对象插入到dio的FormData中来发布它?
我试着像《 Postman 》里那样做,但没用。

var formData = dio.FormData.fromMap({
    'category': categoryId,
    'name': name,
    'price': int.parse(price),
    'color': color,
    'size': sizes,
    'description': description,
    'material': material,
    'countryProducer': countryProducer,
    "style": style,
    "countInStock": int.parse(countInStock),
    "modelCharacteristics[modelHeight]": modelCharacteristics.modelHeight.toInt(),
    "modelCharacteristics[modelWeight]": modelCharacteristics.modelWeight.toInt(),
    "modelCharacteristics[modelSize]": modelCharacteristics.modelSize,)}
qxsslcnc

qxsslcnc1#

事实上,我发布的代码是正确的!有一些内部代码错误导致发布请求不能正常工作。但是,为了将来的软件工程师,我们要回顾一下:
例如,如果您有一个类似于下面这样的复杂JSON对象,您希望使用FormData对其进行POST:

{
"Model" : { "ModelA" : "1", "ModelB" : "2" }
}

然后像这样编写字段

"Model[ModelA]": "1",
"Model[ModelB]": "2"
ocebsuys

ocebsuys2#

要发送json数据和formdata,需要通过json编码将其作为MultiPartFile发送,并将MultiPartFile的内容类型指定为“application/json”,如下所示:

final data = FormData.fromMap({
    "file": await MultipartFile.fromFile(
      path,
      filename: name,
    ),
    "jsonData": MultipartFile.fromString(
      jsonEncode({"name": "user_name"}),
      contentType: MediaType.parse('application/json'),
    ),
  },
);
ivqmmu1c

ivqmmu1c3#

添加其余代码以获得更准确的答案,请查看https://pub.dev/packages/dio文档。

相关问题