我正在尝试使用提供程序包制作购物车页面,我希望每个项目都有一定数量,因此每次我添加新产品时,我都希望它检查列表中是否存在该产品以及是否存在,我希望它计算添加次数,但如果尚未添加到购物车中,则将其添加到购物车中
这是我的Cart

import 'package:flutter/material.dart';

import 'item.dart';

class Cart extends ChangeNotifier{
  List<Item> items = [];
  double totalPrice = 0.0;
  int singleProductCount = 0;

  void add(Item item) {
      items.add(item);
      totalPrice += item.price;
      notifyListeners();
  }

  void remove(Item item) {
    items.remove(item);
    totalPrice -= item.price;
    notifyListeners();
  }

  int get count {
    return items.length;
  }

  double get totalprice {
    return totalPrice;
  }

  int get singleproductCount {
    return singleProductCount;
  }

  List<Item> get basketItems {
    return items;
  }
}
这是将其添加到购物车的IconButton
IconButton(icon: Icon(Icons.add), onPressed: () {
                                  cart.add(Item(name: snapshot.data.documents[index]["name"], price: snapshot.data.documents[index]["price"], imageUrl: snapshot.data.documents[index]["imageUrl"]));
                                }),

最佳答案

我想出了一种方法,但希望有人会提供更好的解决方案。但是实际上我创建了另一个列表来帮助我们解决这种情况。此列表将保存名称(或您想要保存的名称)。然后,我检查该名称是否在列表中,如果是,则返回null,否则将Item添加到列表中。在添加类实例时,这是我目前唯一想到的方法。

List<String> _names = [];
double totalPrice = 0.0;


List<String> get names {
  return _names;
  }



void add(Item item, String newNames) {
    itemList.add(item);
    _names.add(newNames); // add new names to names list
    totalPrice += item.price;
    notifyListeners();
  }
  // If the names list contains any name from the docs already, then don't add anything
  // else add the name to the list along with the Item
       cart.names.contains(snapshot.data.documents[index]["name"])
       ? null
       : cart.add(
        Item(
         name: snapshot.data.documents[index]["name"],
         price: snapshot.data.documents[index]["price"],
         imageUrl: snapshot.data.documents[index]["imageUrl"]
        ),

         snapshot.data.documents[index]["name"]
     );
顺便说一句,如果您不打算使用下划线将属性设为私有(private),则使用get并没有什么意义,例如,int _singleProductCount = 0;

关于flutter - 每个项目的柜台,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63235822/

10-10 23:28