Dart int clamp()
Syntax & Examples

int.clamp() method

The `clamp` method in Dart's `int` class clamps this number to be within the specified range defined by lowerLimit and upperLimit.


Syntax of int.clamp()

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.

Parameters

ParameterOptional/RequiredDescription
lowerLimitrequiredThe lower limit of the range to clamp this number to.
upperLimitrequiredThe upper limit of the range to clamp this number to.

Return Type

int.clamp() returns value of type num.



✐ Examples

1 Clamped number

In this example,

  1. We create an integer variable num with the value 5.
  2. We use the clamp() method to clamp it within the range of 1 to 10.
  3. We then print the clamped number to standard output.

Dart Program

void main() {
  int num = 5;
  int clampedNum = num.clamp(1, 10);
  print('Clamped num: $clampedNum');
}

Output

Clamped num: 5

2 Clamped character code

In this example,

  1. We create an integer variable charCode by getting the character code for 'B'.
  2. We use the clamp() method to clamp it within the character codes of 'A' to 'Z'.
  3. We then print the clamped character code to standard output.

Dart Program

void main() {
  int charCode = 'B'.codeUnitAt(0);
  int clampedCode = charCode.clamp('A'.codeUnitAt(0), 'Z'.codeUnitAt(0));
  print('Clamped character code: $clampedCode');
}

Output

Clamped character code: 66

3 Clamped text length

In this example,

  1. We create a string variable text with the value 'Hello'.
  2. We get its length and then use the clamp() method to clamp it within the range of 1 to 10.
  3. We then print the clamped text length to standard output.

Dart Program

void main() {
  String text = 'Hello';
  int clampedLength = text.length.clamp(1, 10);
  print('Clamped text length: $clampedLength');
}

Output

Clamped text length: 5

Summary

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.