Property can't be unconditionally accessed because the receiver can be null

Viewed 107

I am trying to address the null safety on the following function. Nesting if statements doesn't seem to work.

bool doesTourExceedsVenueCapacity(
  ToursRecord? tourRecord,
  int? venueCapacity,
) {
 
  return tourRecord.passengers > venueCapacity ? true : false;
}
3 Answers

Since both of your values are nullable you have to adjust your code to do the conditional check. Add some guard-like checks before:

bool doesTourExceedsVenueCapacity(
  ToursRecord? tourRecord,
  int? venueCapacity,
) {
  final passengers = tourRecord?.passengers;
  if (venueCapacity == null) return false //adjust return value
  if (passengers == null) return false // adjust return value
 
  return passengers > venueCapacity; // ? true : false unnecessary here
}

It does not work because the statement that you check tourRecord.passengers > venueCapacity contains two values that can be null. ToursRecord? tourRecord.passengers and int? venueCapacity. The question mark is important.

Either Remove null or add condition to handle nullable type in your condition.

Example (By removing nullable type)

bool doesTourExceedsVenueCapacity(
  ToursRecord tourRecord,
  int venueCapacity,
) {
 
  return tourRecord.passengers > venueCapacity ? true : false;
}
Related