Home > front end >  item not removed in list when use list.remove(element) in flutter
item not removed in list when use list.remove(element) in flutter

Time:11-16

I am having trouble removing an item in a list after adding the element.

  List<CartItem> _items = [];
  FirebaseFirestore? _instance;

  void add(BuildContext context, CartItem item) {
    _items.add(item);

    AuthService authService = Provider.of<AuthService>(context, listen: false);
    Map<String, dynamic> cartMap = Map();
    _items.forEach((CartItem item) {
      cartMap['title'] = (item.product as Product).title;
      cartMap['name'] = (item.product as Product).name;
    });

    _instance = FirebaseFirestore.instance;
    _instance!
        .collection('cart')
        .doc(authService.getCurrentUser()) //need to get logged in account's id
        .update({
      'cartProduct': FieldValue.arrayUnion([cartMap])
    }).then((value) {
      print(_items.length);
      notifyListeners();
    });
  }


  void remove(BuildContext context, CartItem item) {
    _items.remove(item);

    AuthService authService = Provider.of<AuthService>(context, listen: false);
    Map<String, dynamic> cartMap = Map();
    cartMap['title'] = (item.product as Product).title;
    cartMap['name'] = (item.product as Product).name;
    _instance = FirebaseFirestore.instance;
    _instance!.collection('cart').doc(authService.getCurrentUser()).update({
      'cartProduct': FieldValue.arrayRemove([cartMap]),
    }).then((value) {

      print(_items.length);
      notifyListeners();
    });
  }

After I do add(context, widget.product) and print _items.length, the result is 1 However, after I do remove(context, widget.product) and print _items.length, the result is still 1.

Consumer<CartService>(
            builder: (context, cart, child) {
              Widget renderedButton;
              if (cart.isProductAddedToCart(widget.product) == false) {
                renderedButton = DefaultButton(
                  text: "Participate",
                  press: () {
                    print(cart.isProductAddedToCart(widget.product));
                    cartService.add(context, CartItem(product: widget.product));
                    print(cart.isProductAddedToCart(widget.product));
                  },
                );
              } else {
                renderedButton = DefaultButton(
                  text: "Delete",
                  press: () {
                    print(cart.isProductAddedToCart(widget.product));
                    cartService.remove(
                        context, CartItem(product: widget.product));
                    print(cart.isProductAddedToCart(widget.product));
                  },
                );
              }
              return renderedButton;

As in the code above, the remove() method is supposed to remove the same item that was added to the list using the add() method.

CodePudding user response:

Just update the remove() to: (only change _items.remove(item); position)

void remove(BuildContext context, CartItem item) {

AuthService authService = Provider.of<AuthService>(context, listen: false);
Map<String, dynamic> cartMap = Map();
cartMap['title'] = (item.product as Product).title;
cartMap['name'] = (item.product as Product).name;
_instance = FirebaseFirestore.instance;
_instance!.collection('cart').doc(authService.getCurrentUser()).update({
  'cartProduct': FieldValue.arrayRemove([cartMap]),
}).then((value) {

/// todo check firebase collection's deletion success first
_items.remove(item);

  print(_items.length);
  notifyListeners();
});
}

CodePudding user response:

The item you're adding to the list may not be the same instance of the item you're removing. Make sure the item object/class have equality and hashcode implementation to compare the two items properly.

If you don't have control over the object, the following approach can be an easier alternative:

_items.removeWhere((_item) => _item.property == item.property);

^ where property can be the id of the product.

  • Related