【问题标题】:type 'List<List<dynamic>>' is not a subtype of type 'String' in type cast)type 'List<List<dynamic>>' 不是类型转换中类型 'String' 的子类型)
【发布时间】:2021-08-29 06:04:33
【问题描述】:

调试代码时出现此错误

类型“List”不是类型转换中“String”类型的子类型)

我不愿意在正文中添加 json.encode(data),那是因为 服务器不将请求视为原始,所以我必须将正文指定为 form-data。

请帮忙

class CartConfirmatinoAPi {
  static const API = kDevelopmentMobile;
  static const key = {
    'KEY': "***************************",
    "Content-Type": "application/x-www-form-urlencoded"
  };

  Future orderConfirmation(CartConfirmationModel cd, orderNotifyData) {
    var dataMap = new Map<String, dynamic>();

    final List orders = [];

    for (var item in orderNotifyData.items) {
      var productMap = {
        'product_id': item.productId,
        'qty': item.qty,
      };
      orders.add(productMap);
    }

    dataMap['customer_id'] = cd.customerId;
    
    dataMap['orderLine'] = orders; **// this is the line is causing the problem**

    return http // 
        .post(API + '/orders/create', headers: key, body: dataMap)
        .then((data) {
      if (data.statusCode == 200) {
        final jsonData = json.decode(data.body);

        return jsonData['Result'];
      }
    });
  }
}

API 要求

$result = [];
        
        $result['customer_id'] = $this->input->post('customer_id', true);

        $result['orderLine'] = $this->input->post('orderLine');

        $message = [
            'Code'    => 200,
            'Result'  => $result ? $result : []
        ];
        $this->response($message,REST_Controller::HTTP_OK);

【问题讨论】:

  • 首先尝试打印orders并匹配api要求的格式
  • @PrabhanshuTiwari - 这是我打印订单时的输出
  • [{product_id: 1, qty: 1}, {product_id: 2, qty: 1}, {product_id: 26, qty: 2}]
  • 又是什么api需求格式?
  • 更新了我的代码,添加了 API requiremtns

标签: php flutter dart


【解决方案1】:

根据http包文档

[body] 设置请求的正文。它可以是 [String]、[List] 或 一个 [Map]

在您的代码中,dataMap 的类型为 Map&lt;String, dynamic&gt;。在运行时,您的地图的值是Map&lt;String, List&lt;dynamic&gt;&gt; 类型的某个点。所以它尝试将List&lt;dynamic&gt; 转换为String,这显然是不可能的。

这解释了为什么当您评论 dataMap['orderLine'] = orders 时您的代码可以正常工作。 由于cd.customerId 可能是一个字符串,在运行时dataMap 的类型是Map

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 2019-05-02
    • 2021-12-29
    • 2023-01-08
    • 2023-03-25
    • 1970-01-01
    • 2021-10-23
    • 2020-12-21
    • 2021-01-22
    相关资源
    最近更新 更多