首页 > 解决方案 > 在颤振中将请求复杂的json发布到api

问题描述

我有这个 json 我想发布到一个 api 但我不确定它是如何完成的..这是请求的样子:

  {
    "products": [
        {"id":1, "qty": 1},{"id":2, "qty": 1}
    ],
    "vendor_id": 1,
    "notes": " ",
    "address": ""
}

这是我用来映射请求的请求类:

    class Order{

  int vendor_id;
  String address ,notes ;
  List<OrderProduct> products;

  Order({this.products , this.address , this.notes , this.vendor_id});

  Map<String, dynamic> toMap() {
    return {
      'vendor_id': vendor_id,
      'address': address,
      'notes': notes,
      'products': products,
    };
  }


}

class OrderProduct{
  int id , qty ;
  OrderProduct({this.id , this.qty});
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'qty': qty,
    };
  }
}

我错过了什么?

标签: jsonapidictionaryflutterhttp-post

解决方案


就这样吧json.encode(myArr),例如

 Map<String, String> params = {
      "mobile": userNameController.text,
      "password": passwordController.text,
      "deviceid": '${fcmToken}',
    };
 Future<String> postRequest(var url, {var postParams}) async {
    return http
        .post(url, body: json.encode(postParams))// do json encoding here 
        .then((http.Response response) {
      final int statusCode = response.statusCode;
      print("postParams " + json.encode(postParams));
      print("statusCode " + '${statusCode} ${response.body}');
      if (statusCode < 200 || statusCode > 400 || json == null) {
        throw new Exception("Error while fetching data");
      }
      print(response.request);
      return response.body;
    });
  }

推荐阅读