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?
CodePudding user response:
Assuming the method CartItem.toJson() is called at Store.instance.addItemToCart(_item), the variable _item never receives a color, thus making the color field null. This causes the error, because the exclamation mark in the toJson method "color": converColorToString(color!) tells dart to assume that the color value is not null, but it actually is because it was never initialized.
To fix this issue, you would have to initialize your item value like that:
CartItem _item = CartItem()
..productId = _product.productId
..productName = _product.productName
..productPrice = _price
..quantity = 1
..color = Colors.red //Provide a value for color, so it is not null
..totalPrice = _price;
UPDATE 1
If you want to have a null value in the color field, then you'd have to change the toJson method. You could either only put the color field to the json map if the value is not null, or explicitely assign null.
option:
Map<String, dynamic> toJson() { Map<String, dynamic> json = { //........, "size": size, }; if(color != null){ json["color"] = converColorToString(color); } return json;};
This way, the color field is only present in the json if it is not null.
option:
Map<String, dynamic> toJson() { Map<String, dynamic> json = { //........, "size": size, "color": color == null ? null : converColorToString(color), }; return json;};
This way, if color is null, the color field in the json map is explicitely set to null.
