Ardeshir ojan
Ardeshir ojan

Reputation: 2409

The operator '>=' can't be unconditionally invoked because the receiver can be 'null'. flutter null safety

I have the following code

 if (myCart?.cart?.cartDetails != null &&
    myCart?.cart?.cartDetails!
            .indexWhere((element) => element.productId == productId)  >=
        0) {
  return true;
}

this code gets an error in ">=" part saying it can be null. How can I fix this?

Upvotes: 0

Views: 245

Answers (2)

Stewie Griffin
Stewie Griffin

Reputation: 5608

indexWhere can return null in your case and the >= operator cannot be used with a null value. Try the following code:

final index = myCart?.cart?.cartDetails
    ?.indexWhere((element) => element.productId == productId);

if (index != null && index >= 0) {
  return true;
}

Upvotes: 2

Hamza Azam
Hamza Azam

Reputation: 332

I think its because element.productId can be null. can you try element.productId! == productId or element.productId? == productId

Upvotes: 0

Related Questions