简体   繁体   中英

How to post an object in formData in flutter Dio package?

I have a "modelCharacteristics" object that contains modelHeight, modelWeight, and modelSize objects. How do I insert a JSON object to dio's FormData to post it?

I tried to do it like in Postman but that does not work.

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,)}

In fact, the code I posted was correct! There were internal code errors that did not let the post request work properly. However, to recap for future software engineers:

If you have, for example, a complex JSON object like this that you want to POST using FormData:

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

then write your fields like these

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

For sending json data with formdata, you will need to send it as a MultiPartFile by json encoding it and specifying the content type of Multipartfile to "application/json". Like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM