62 lines
1.6 KiB
Dart
62 lines
1.6 KiB
Dart
class CartResponse {
|
|
final bool success;
|
|
final Map<String, CartItem> cart;
|
|
|
|
CartResponse({required this.success, required this.cart});
|
|
|
|
factory CartResponse.fromJson(Map<String, dynamic> json) {
|
|
final cartMap = <String, CartItem>{};
|
|
|
|
if (json['cart'] != null) {
|
|
if (json['cart'] is Map<String, dynamic>) {
|
|
// Case 1: cart is a Map
|
|
(json['cart'] as Map<String, dynamic>).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<String, dynamic>) {
|
|
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<String, dynamic> 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<String, dynamic> toJson() {
|
|
return {
|
|
'product_id': productId,
|
|
'quantity': quantity,
|
|
'name': name,
|
|
'price': price,
|
|
};
|
|
}
|
|
}
|