class CartResponse { final bool success; final Map cart; CartResponse({required this.success, required this.cart}); factory CartResponse.fromJson(Map json) { final cartMap = {}; if (json['cart'] != null) { if (json['cart'] is Map) { // Case 1: cart is a Map (json['cart'] as Map).forEach((key, value) { cartMap[key] = CartItem.fromJson(value); }); } else if (json['cart'] is List) { // Case 2: cart is a List for (var i = 0; i < (json['cart'] as List).length; i++) { final item = (json['cart'] as List)[i]; if (item is Map) { cartMap[i.toString()] = CartItem.fromJson(item); } } } } return CartResponse(success: json['success'] ?? false, cart: cartMap); } } class CartItem { final int productId; final int quantity; final String name; final String price; CartItem({ required this.productId, required this.quantity, required this.name, required this.price, }); factory CartItem.fromJson(Map json) { return CartItem( productId: int.tryParse(json['product_id']?.toString() ?? '0') ?? 0, quantity: int.tryParse(json['quantity']?.toString() ?? '0') ?? 0, name: json['name']?.toString() ?? '', price: json['price']?.toString() ?? '0', ); } Map toJson() { return { 'product_id': productId, 'quantity': quantity, 'name': name, 'price': price, }; } }