How do I generate random numbers in Dart?

try this, you can control the min/max value :

NOTE that you need to import dart math library.

import 'dart:math';

void main() {
  
  int random(int min, int max) {
    return min + Random().nextInt(max - min);
  }

  print(random(5, 20)); // Output : 19, 5, 15.. (5 -> 19, 20 is not included)
}

Use Random class from dart:math:

import 'dart:math';

main() {
  var rng = Random();
  for (var i = 0; i < 10; i++) {
    print(rng.nextInt(100));
  }
}

This code was tested with the Dart VM and dart2js, as of the time of this writing.


You can achieve it via Random class object random.nextInt(max), which is in dart:math library. The nextInt() method requires a max limit. The random number starts from 0 and the max limit itself is exclusive.

import 'dart:math';
Random random = new Random();
int randomNumber = random.nextInt(100); // from 0 upto 99 included

If you want to add the min limit, add the min limit to the result

int randomNumber = random.nextInt(90) + 10; // from 10 upto 99 included

Tags:

Random

Dart