coerceIn method
T
coerceIn(
- T minimumValue, [
- T? maximumValue
Ensures that this value lies in the specified range
minimumValue..maximumValue.
Return this value if it's in the range, or minimumValue if this value
is less than minimumValue, or maximumValue if this value is greater
than maximumValue.
print(10.coerceIn(1, 100)) // 10
print(0.coerceIn(1, 100)) // 1
print(500.coerceIn(1, 100)) // 100
10.coerceIn(100, 0) // will fail with ArgumentError
Implementation
T coerceIn(T minimumValue, [T? maximumValue]) {
if (maximumValue != null && minimumValue > maximumValue) {
throw ArgumentError(
'Cannot coerce value to an empty range: '
'maximum $maximumValue is less than minimum $minimumValue.',
);
}
if (this < minimumValue) return minimumValue;
if (maximumValue != null && this > maximumValue) return maximumValue;
return this;
}