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;
}
CodePudding user response:
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.
CodePudding user response:
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;
}
CodePudding user response:
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
}