Khaled
Khaled

Reputation: 35

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

 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

Upvotes: 0

Views: 47

Answers (2)

Vu Thanh
Vu Thanh

Reputation: 398

Maybe this list is empty.

cubit.getCartModel!.data

and you are accessing it with

index=4

Upvotes: 0

jraufeisen
jraufeisen

Reputation: 3877

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.

Upvotes: 0

Related Questions