The `clamp` method in Dart's `int` class clamps this number to be within the specified range defined by lowerLimit and upperLimit.
The syntax of int.clamp() method is:
num clamp(num lowerLimit num upperLimit)
This clamp() method of int returns this num clamped to be in the range lowerLimit-upperLimit.
Parameter | Optional/Required | Description |
---|---|---|
lowerLimit | required | The lower limit of the range to clamp this number to. |
upperLimit | required | The upper limit of the range to clamp this number to. |
int.clamp() returns value of type num
.
In this example,
num
with the value 5.clamp()
method to clamp it within the range of 1 to 10.void main() {
int num = 5;
int clampedNum = num.clamp(1, 10);
print('Clamped num: $clampedNum');
}
Clamped num: 5
In this example,
charCode
by getting the character code for 'B'.clamp()
method to clamp it within the character codes of 'A' to 'Z'.void main() {
int charCode = 'B'.codeUnitAt(0);
int clampedCode = charCode.clamp('A'.codeUnitAt(0), 'Z'.codeUnitAt(0));
print('Clamped character code: $clampedCode');
}
Clamped character code: 66
In this example,
text
with the value 'Hello'.clamp()
method to clamp it within the range of 1 to 10.void main() {
String text = 'Hello';
int clampedLength = text.length.clamp(1, 10);
print('Clamped text length: $clampedLength');
}
Clamped text length: 5
In this Dart tutorial, we learned about clamp() method of int: the syntax and few working examples with output and detailed explanation for each example.