My cartitem object looks like:
class CartItem {
String? productId;
String? productName;
double? productPrice;
int? quantity;
Color? color;
String? size;
double? totalPrice;
CartItem({
.....
this.color,
this.size,
});
factory CartItem.fromJson(Map<String, dynamic> json) => CartItem(
......
color: converStringToColor(json["color"]),
size: json["size"],
totalPrice: json["totalPrice"],
);
Map<String, dynamic> toJson() => {
.......
"color": converColorToString(color!),
"size": size,
};
}
On the other hand my product object has multiple fields of which one is hasMultipleVariants (boolean).
If hasMultipleVariants is true then I will show a pop up asking to select color and sizes. If not I will take necessary data from product and map it to cartItem. I'm doing it like below:
Product _product = Search().search(search);
if (_product.hasMultipleVariants == true) {
showDialog(
context: context,
builder: (context) {
return ProductDetailsDialog(
product: _product,
);
},
);
} else {
final _price = _product.dicountedPrice! < _product.price!
? _product.dicountedPrice
: _product.price;
CartItem _item = CartItem()
..productId = _product.productId
..productName = _product.productName
..productPrice = _price
..quantity = 1
..totalPrice = _price;
Store.instance.addItemToCart(_item); // saving to local storage of phone
EventStream.putEvent(Event(EventType.CART_UPDATED));
}
But this is throwing a Unhandled Exception: Null check operator used on a null value from CartItem.toJson() error. How can I solve this issue?