nextInt method

  1. @override
int nextInt(
  1. int max
)
override

Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive.

Implementation note: The default implementation supports max values between 1 and (1<<32) inclusive.

Example:

var intValue = Random().nextInt(10); // Value is >= 0 and < 10.
intValue = Random().nextInt(100) + 50; // Value is >= 50 and < 150.

Implementation

@override
int nextInt(int max) {
  if (max < 0 || max > _bit32) {
    throw ArgumentError.value(max, 'max');
  }
  if (max == 0x100000000) {
    return nextUint32();
  }
  var attempts = 0;
  while (true) {
    final x = nextUint32();
    final samplingMax = _bit32 ~/ max * max;
    if (x < samplingMax || attempts >= 100) {
      return x % max;
    }
    attempts++;
  }
}