Home > database >  RangeError (index): Invalid value: Only valid value is 0: 4 when trying to add to cart
RangeError (index): Invalid value: Only valid value is 0: 4 when trying to add to cart

Time:11-17

 ElevatedButton(
    style: ElevatedButton.styleFrom(
    shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10))),
        onPressed: () {
            cubit.addItemToCart(
                id: cubit.getCartModel!.data[index].id);
        },
        child: Text(LocaleKeys.addToCart.tr()),
 )

I'm trying to add item to cart so this RangeError Appears to me if anyone know how to solve it, I'll Aprreciate his Effort

CodePudding user response:

Your range error comes from this line

cubit.getCartModel!.data[index]

It tells you that index is

  • larger than or equal to the number of elements in your list cubit.getCartModel
  • or smaller than zero

This is a problem because you can only select list elements in a range from 0...length - 1.

CodePudding user response:

Maybe this list is empty.

cubit.getCartModel!.data

and you are accessing it with

index=4

  • Related