首页 > 解决方案 > 传递 LIST (Flutter) 时 json 原始正文中的 HTTP POST 出错

问题描述

我正在尝试通过执行 HTTP 请求在 JSON 原始正文中发布订单项目列表。预期列表如下。

"orderItems": [
        {
            "userId": "a130b5be-1eda-4eae-a599-6cb8b6256c4e",
            "title": "Tenku remastered",
            "quantity": 1,
            "image": "http://res.cloudinary.com/dev-empty/image/upload/v1629881848/podenl8wj53oclisitbe.jpg",
            "price": 11.0
        },
        {
            "userId": "a130b5be-1eda-4eae-a599-6cb8b6256c4e",
            "title": "Selted chino trousers polo",
            "quantity": 1,
            "image": "http://res.cloudinary.com/dev-empty/image/upload/v1629881954/ky4sku7df15446u20x9x.jpg",
            "price": 19.0
        }
    ]

为此 JSON 对象构建模型类并使用 toJson() 传递对象值。

型号类:

class CartItems {
  
  String? userId;
  String? title;
  int? quantity;
  String? image;
  double? price;

  CartItems({
    
    this.userId,
    this.title,
    this.quantity,
    this.image,
    this.price,
  });

  CartItems.fromJson(Map<String, dynamic> json) {
    
    userId = json['userId'].toString();
    title = json['title']?.toString();
    quantity = json['quantity']?.toInt();
    image = json['image']?.toString();
    price = json['price']?.toDouble();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['userId'] = this.userId;
    data['title'] = this.title;
    data['quantity'] = this.quantity;
    data['image'] = this.image;
    data['price'] = this.price;
    return data;
  }
}

Added items on **cartList** which is an instance of the observable list

我试图通过这样的列表"orderItems": cart.cartList.map((element) => element.toJson()).toList()

Map<String, dynamic> orderDetails = {
      "userId": auth.userData.value.id,
      "name": auth.userData.value.name,
      "email": auth.userData.value.email,
      "phone": map['phone'],
      "address": map['address'],
      "city": map['city'],
      "state": map['state'],
      "zipcode": map['zip'],
      "totalPrice": cart.cartTotal.toString(),
      "orderItems": cart.cartList.map((element) => element.toJson()).toList()
    };

对于这一行,它给出了一个错误

type 'List<Map<String, dynamic>>' is not a subtype of type 'String' in typecast

如果我使用字符串插值将整段代码放入字符串中或将这些对象绑定到 jsonEncode 中,那么它会给出另一个错误{"err":"orderItems.map is not a function"},但它会将空列表发布到服务器上。

完整代码:

Future<TransactionResponse> makeCheckout(Map<String, dynamic> map) async {
    AuthController auth = Get.find();
    CartController cart = Get.find();
    ProductController prodCtrl = Get.find();
    final box = GetStorage();

    final token = box.read('token');
    // print(token);
    String url = baseUrl + makeOrderUrl;
    Uri uri = Uri.parse(url);
    // int _cost = cost ~/ 100;
    // Map<String, dynamic> paymentData = {
    //   "email": auth.userData.value.email,
    //   // "id": _cost.toString(),
    // };

    Map<String, dynamic> orderDetails = {
      "userId": auth.userData.value.id,
      "name": auth.userData.value.name,
      "email": auth.userData.value.email,
      "phone": map['phone'],
      "address": map['address'],
      "city": map['city'],
      "state": map['state'],
      "zipcode": map['zip'],
      "totalPrice": cart.cartTotal.toString(),
      "orderItems": cart.cartList.map((element) => element.toJson()).toList()
    };
    print("---:");
    print(orderDetails);
    print(":---");
    Map<String, String> headers = {"Authorization": token};
    try {
      http.Response response = await http.post(
        uri,
        body: jsonEncode(orderDetails),
        headers: headers,
      );

      //I'm receiving statusCode 308, and handling manually using below code
      if (response.statusCode == 308) {
        final getResponse = await http.post(
          Uri.parse(baseUrl + response.headers["location"]!),
          body: orderDetails,
          headers: headers,
        );

        print(getResponse.statusCode);
        final getResponseData = jsonDecode(getResponse.body);

        if (getResponse.statusCode == 200) {
          print(getResponseData['msg']);
          cart.cartList.clear();
          prodCtrl.getMyOrder();

          return TransactionResponse(
            message: getResponseData['msg'],
            success: true,
          );
        } else {
          print(getResponse.body);

          return TransactionResponse(
            message: getResponse.body,
            success: false,
          );
        }
      } else {
        if (response.statusCode == 200) {
          cart.cartList.clear();
          prodCtrl.getMyOrder();

          return TransactionResponse(
            message: response.body,
            success: true,
          );
        } else {
          return TransactionResponse(
            message: response.body,
            success: false,
          );
        }
      }
    } on Exception catch (e) {
      print(e.toString());
      throw e;
    } catch (e) {
      print(e.toString());
      throw e;
    }
  }

这个问题的解决方案是什么?我尝试了几种解决方案,但没有奏效。提供任何解决方案都非常重要。

标签: jsonflutterhttpdartpost

解决方案


推荐阅读