首页 > 解决方案 > 以复杂对象为主体的 Dart HTTP Post

问题描述

Dart http 包的 post 方法只接受 String、List 或 Map 作为请求体。我需要将此列表作为正文发送

     List item = widget.product
    .map((prod) => {
    "product_id": prod.id,
  "product_name": prod.title,
"product_quantity": prod.quantity,
"product_reference": prod.reference
   }).toList();

在邮递员中,我会将主体构建为原始 json

{"id_customer": "null",
"id_adresse": "null",
"id_carrier": "155",
"secure_key": "null",
"payment": "Paiement à la livraison",
"total_paid": "311.0",
"total_product": "298.0",
"total_shipping": "7.0",
"tax": "0.6",
"products": [{"product_id": "5444",
            "product_name": "Batterie adaptable pour ordinateur portable  Asus X550A 2200mAh",
            "product_quantity": "1",
            "product_reference": "null"},
            {"product_id": "5433",
            "product_name": "Batterie originale pour ordinateur portable Asus K52 4400mAh",
            "product_quantity": "1",
            "product_reference": "null"}]}

这是我的尝试

void addorders(String id , String id_adresse,String secure_key,String id_carrier,String paiement,double total,double total_product,double total_shipping,double tax, List products) async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'token';
    final value = prefs.get(key ) ?? 0;

    String myUrl =  "$serverUrl/orders";
final String prod=products.toString();

    http.post(myUrl,
        headers: {
          'Accept':'application/json',
          //"content-type": "application/json",
          'Authorization' : 'JWT $value'
        },
        body: {
          "id_customer":"$id",
          "id_adresse":"$id_adresse",
          "id_carrier":"$id_carrier",
          "secure_key":"$secure_key",
          "payment":"$paiement",
          "total_paid":"$total",
          "total_product":"$total_product",
          "total_shipping":"$total_shipping",
          "tax":"$tax",
          "products":"$prod",

        }).then((response){
     // print('Response status : ${response.statusCode}');
      print('Response body ');
      print(response.request);

     // print('Response body : ${id_carrier}');
    }
    );
  }

我使用字符串编码 = json.encode(theMap) 但同样的问题我的 api 不读取列表产品请帮助。

标签: jsonhttpflutterpostdart

解决方案


您应该使用转换器来获取对您的 json 数据进行数学运算并处理它的 dart 类,而不是像您那样传递您的值。

例如,您可以将此JSON 用于 Dart。您只需要从邮递员那里粘贴您的 json 数据即可恢复您的飞镖课程

在你只需要调用toJson()你的类的方法来获取你的请求正文的 Map 之后


推荐阅读