checkValidRange static method Null safety

int checkValidRange(
  1. int start,
  2. int? end,
  3. int length,
  4. [String? startName,
  5. String? endName,
  6. String? message]
)

Check that a range represents a slice of an indexable object.

Throws if the range is not valid for an indexable object with the given length. A range is valid for an indexable object with a given length

if 0 <= [start] <= [end] <= [length]. An end of null is considered equivalent to length.

The startName and endName defaults to "start" and "end", respectively.

Returns the actual end value, which is length if end is null, and end otherwise.

Implementation

static int checkValidRange(int start, int? end, int length,
    [String? startName, String? endName, String? message]) {
  // Comparing with `0` as receiver produces better dart2js type inference.
  // Ditto `start > end` below.
  if (0 > start || start > length) {
    startName ??= "start";
    throw RangeError.range(start, 0, length, startName, message);
  }
  if (end != null) {
    if (start > end || end > length) {
      endName ??= "end";
      throw RangeError.range(end, start, length, endName, message);
    }
    return end;
  }
  return length;
}