Search code examples
flutterdartdart-null-safety

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


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;
}

Solution

  • 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
    }