我想将我的对象转换为 JSON,所以我实现了以下代码
import "package:behoove/models/product.dart";
class Order {
Product _product;
int _quantity;
int _id;
Order(this._product, this._quantity, this._id);
int get id => _id;
int get quantity => _quantity;
Product get product => _product;
double get orderPrice => _quantity * double.parse(_product.discountedPrice ?? _product.price);
Map<String, dynamic> toJson() => {
"id": _product.id.toString(),
"name": _product.name,
"price": _product.price,
"quantity": _quantity.toString(),
"attributes": {},
"conditions": []
};
}
Run Code Online (Sandbox Code Playgroud)
来自应用程序的 JSON 是
{id: 9, name: GoldStar Classic 032, price: 1200, quantity: 1, attributes: {}, conditions: []}}
Run Code Online (Sandbox Code Playgroud)
但来自 DartPad …
我想在 if
语句,但我无法这样做。
下面是我的代码片段。
Run Code Online (Sandbox Code Playgroud)void addOrderToCart(Product product, int quantity, String color, String size) { _lastOrder = Order(product, quantity, _orderId++, color, size); _orders.forEach((element) { if(element.product.id == _lastOrder.product.id){ element.colors.add(color); element.sizes.add(size); element.quantity = element.quantity + quantity; notifyListeners(); return; } }); _orders.add(_lastOrder); notifyListeners(); }
谢谢。