在Flutter中将请求复杂的json发布到api

时间:2019-11-20 09:49:30

标签: json api dictionary flutter http-post

我有这个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,
    };
  }
}

我错过了什么?

1 个答案:

答案 0 :(得分:0)

就像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;
    });
  }