添加项目数量(e-commerce/shop 应用程序)

Add the quantity of items (e-commerce/shop app)

我目前正在开发电子商务应用程序,

我正在尝试增加用户尝试购买的商品数量,然后在 "items Cart" 中显示它们,但相反,我得到了多次相同的商品。

cart_Items_Screen

这是我使用的代码:

FlatButton(
                onPressed: () {
                  _addToCart(context, this.widget.product);
                },
                textColor: Colors.redAccent,
                child: Row(
                  children: [
                    Text('Add to Cart'),
                    IconButton(
                        icon: Icon(Icons.shopping_cart), onPressed: () {}),
                  ],
                ),
              ),
_addToCart(BuildContext context, Product product) async {
    var result = await _cartService.addToCart(product);
    if (result > 0) {
      print(result);
      _showSnackMessage(Text(
        'Item added to cart successfully!',
        style: TextStyle(color: Colors.green),
      ));
    } else {
      _showSnackMessage(Text(
        'Failed to add to cart!',
        style: TextStyle(color: Colors.red),
      ));
    }
  }
addToCart(Product product) async {
    List<Map> items =
        await _repository.getLocalByCondition('carts', 'productId', product.id);
    if (items.length > 0) {
      product.quantity = items.first['productQuantity'] + 1;
      return await _repository.updateLocal(
          'carts', 'productId', product.toMap());
    }
    print(items);
    product.quantity = 1;
    return await _repository.saveLocal('carts', product.toMap());
  }

有没有人有过这样的经历? 谁能帮我?

您用什么来存放物品?本地数据库还是只是一个列表?在任何情况下,您都需要先检查您的项目包含,然后如果是,您只需要更新数量,如果不是,您需要添加为新元素。我的意思是,据我了解,您使用 items.length > 0 检查它,它看起来太笼统了,items.contains('productId') 使用起来会更具体。