I have data from API like this :
{
"data": {
"1": [
{
"id": 31,
"customer_id": 2,
"product_variant_id": 123,
"quantity": 5,
"partner_id": 1
},
{
"id": 30,
"customer_id": 2,
"product_variant_id": 109,
"quantity": 2,
"partner_id": 1
}
],
"3": [
{
"id": 29,
"customer_id": 2,
"product_variant_id": 107,
"quantity": 8,
"partner_id": 3,
}
]
},
"code": 200,
"msg": "Data All Cart"
}
and here’s the cartModel :
class CartMetadata {
CartMetadata({
required this.data,
required this.code,
required this.msg,
});
final Map<String, List<CartModel>> data;
final int code;
final String msg;
factory CartMetadata.fromJson(Map<String, dynamic> json) => CartMetadata(
data: Map.from(json["data"]).map((k, v) => MapEntry<String, List<CartModel>>(k,
List<CartModel>.from(v.map((x) => CartModel.fromJson(x))))),
code: json["code"],
msg: json["msg"],
);
Map<String, dynamic> toJson() => {
"data": Map.from(data).map((k, v) => MapEntry<String, dynamic>(k,
List<dynamic>.from(v.map((x) => x.toJson())))),
"code": code,
"msg": msg,
};
}
class CartModel {
CartModel({
required this.id,
required this.customerId,
required this.productVariantId,
required this.quantity,
required this.partnerId,
});
final int id;
final int customerId;
final int productVariantId;
final int quantity;
final int partnerId;
factory CartModel.fromJson(Map<String, dynamic> json) => CartModel(
id: json["id"],
customerId: json["customer_id"],
productVariantId: json["product_variant_id"],
quantity: json["quantity"],
partnerId: json["partner_id"],
);
Map<String, dynamic> toJson() => {
"id": id,
"customer_id": customerId,
"product_variant_id": productVariantId,
"quantity": quantity,
"partner_id": partnerId,
};
}
I was using this variable :
final jsonMap = CartMetadata.fromJson(jsonDecode(response.body));
CartModel? cart;
And the result I need is specific data with specific id, example for id == 30 :
cart = { "id": 30, "customer_id": 2, "product_variant_id": 109,
"quantity": 2, "partner_id": 1 }
I know I should used ‘where’ function, but I already try and the problem I should use array on jsonMap.data[array].
Anyone can give advice?
4
Answers
use
which is already written in your data class to get a json in that specified format
In my opinion just use cart.<variable_name> to access instead of doing same work multiple time json if you really need use the above wholde code will be
try this might help but also try other might also have more easy to follow
then try to use entries and get the value data
as the result data would get is id 31
Just use,
Way: 1 – use map and array
Way: 2 – Make extension
usage,
function calling
Pass item id
Result ScreenShot