Search code examples
flutterlistviewflutter-getx

Cannot remove the last item in the ListView Flutter


I have a ListView containing the observable list var cartItems = <CartItem>[].obs;, when I tried to remove the last item in the ListView, I got error RangeError (index): Invalid value: Valid value range is empty: 0 and it was undone. Anyone can show me how to fix it? Thanks in advance. This is my code to hold the ListView:

return Obx(() {
      if (_cartController.isLoading == false) {
        if (_cartController.cartItems.length == 0) {
          return Center(
            child: Text("Your cart is empty."),
          );
        }
        return Scaffold(
          backgroundColor: Colors.white,
          body: ListView.separated(
            ...
            itemBuilder: (context, index) {
              return Slidable(
                endActionPane: ActionPane(
                  motion: ScrollMotion(),
                  children: [
                    SlidableAction(
                      onPressed: (context) {
                        setState(() {
                          _cartController.cartItems.removeAt(index);
                        });
                        _cartController
                            .removeFromCart(
                                userId: widget.user.id,
                                productId:
                                    _cartController.cartItems[index].item.id)
                            .then((value) {...});
                      },
                      ...
                    ),
                  ],
                ),
                child: GestureDetector(
                  onTap: () => Get.to(() => ProductDetailsScreen(
                      product: _cartController.cartItems[index].item)),
                  child: _itemCard(
                      cartItem: _cartController.cartItems[index], index: index),
                ),
              );
            },
            ...
          ),
          ...
        );
      } else {
        ...
      }
    });

Solution

  • The issue is with your onPressed function. what does the removeFromCart method do? I presume it's calling some api. The problem here is that you are removing the item from cartItems array using removeAt(index) method. Then you are calling removeFromCart method on your controller. And, arguments for that removeFromCart method includes productId: _cartController.cartItems[index].item.id.

    The error is coming from that line, when item count is 1, here is what your code does:

    1. It removes the item at index = 0 on _cartController.cartItems.removeAt(index); line.
    2. Then proceeds to call to _cartController.removeFromCart() which has argument called productId. But, now your cartItems array is empty - you already removed the item in the previous step. So, it will throw an exception.

    Solution: only remove the cartItem at specific index after completing your api call or when that removeFromCart() promise full fills.