小编cod*_*er0的帖子

如何在flutter中将对象转换为json?

我想将我的对象转换为 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)

来自应用程序的屏幕截图 JSON

但来自 DartPad …

json object dart flutter

3
推荐指数
1
解决办法
5626
查看次数

Dart:在foreach循环中从if退出函数

我想在 if语句,但我无法这样做。

下面是我的代码片段。

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();
  }
Run Code Online (Sandbox Code Playgroud)

谢谢。

foreach loops break dart flutter

3
推荐指数
2
解决办法
2747
查看次数

标签 统计

dart ×2

flutter ×2

break ×1

foreach ×1

json ×1

loops ×1

object ×1