skip to Main Content

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


  1. use

    cart.toJson()
    

    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

    final jsonMap = CartMetadata.fromJson(jsonDecode(response.body));
    
    CartModel? cart = jsonMap.data['1'].single; //1 is the key of the data and if you want specific cart use where condition or get through a index like [0] {int inside}
    
    Login or Signup to reply.
  2. try this might help but also try other might also have more easy to follow

    // put the data to your model e.g.
    
    final converttoModel = CartMetadata.fromJson(jsondata);
    

    then try to use entries and get the value data

         final find = converttoModel.data.entries
         .map((e)=> e.value)
         .map((e) => e.where((e)=> e.id == 31)
         .first.toJson());
     
      //  then print the data or log it on debug console
       log(find.first.toString());
    

    as the result data would get is id 31

    {id: 31, customer_id: 2, product_variant_id: 123, quantity: 5, partner_id: 1}
    
    Login or Signup to reply.
  3. Just use,

    Way: 1 – use map and array

    jsonMap.data["1"]?[1]
    // "1" is key of data or partner_id
    // 1 is index of array
    // ? is for null safety
    

    Way: 2 – Make extension

    extension GetCartItem on CartMetadata {
      CartModel? cartItem(int partnerId, int index){
        return data["$partnerId"]?[index];
      }
    }
    

    usage,

    jsonMap.cartItem(1,1) // return CartItem or null, Don't forget to import extension :)
    
    Login or Signup to reply.
  4. function calling

    ElevatedButton(
                  onPressed: () {
                    findItem(30);
                  },
                  child: Text("click")),
    

    Pass item id

     findItem(int id) {
            final cartMeta = CartMetadata.fromJson(json);
            CartModel? data1;
            cartMeta.data.forEach((key, value) {
              value.forEach((element) {
                if (element.id == id) data1 = element;
              });
            });
            print("result ==> ${data1?.toJson()}");
          }
    

    Result ScreenShot
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search