You may have often wondered how to generate a random number from within a certain range. This is exactly what we will look at in this recipe; we will obtain a random number that resides in an interval between a minimum (min) and maximum (max) value.
This is simple; look at how it is done in random_range.dart
:
import 'dart:math'; var now = new DateTime.now(); Random rnd = new Random(); Random rnd2 = new Random(now.millisecondsSinceEpoch); void main() { int min = 13, max = 42; int r = min + rnd.nextInt(max - min); print("$r is in the range of $min and $max"); // e.g. 31 // used as a function nextInter: print("${nextInter(min, max)}"); // for example: 17 int r2 = min + rnd2.nextInt(max - min); print("$r2 is in the range of $min and $max"); // e.g. 33 }
The Random
class in dart:math
has a method nextInt(int max)
, which returns a random positive integer between 0 and max (not included). There is no built-in function for our question but it is very easy, as shown in the previous example. If you need this often, use a function nextInter
for it, as shown in the following code:
int nextInter(int min, int max) { Random rnd = new Random(); return min + rnd.nextInt(max - min); }
The variable rnd2
shows another constructor of Random
, which takes an integer as a seed for the pseudo-random calculation of nextInt
. Using a seed makes for better randomness, and should be used if you need many random values.