How to Generate Random Numbers and range of numbers in Dart or Flutter Programming with example
This tutorial shows multiple methods for generating random numbers in the Dart programming language.
A random number is a unique value generated within a specified range, ensuring unpredictability for various requests. The generated number always falls within the provided range of values.
Dart Random Number Generator Example
Dart’s dart:math
library includes a Random class for random number generation. It offers the nextInt
method, which accepts a maximum value and returns a random number.
int nextInt(int max)
The minimum number is implicitly taken as zero, while the maximum number is the given max value.
Here’s a simple example of generating random numbers:
import 'dart: math';
main() {
var random = Random();
print(random.nextInt(10)); //Random number between 0 to 10
print(random.nextInt(100)); //Random number between 0 to 100
print(random.nextInt(200)); //Random number between 0 to 100
print(random.nextInt(1000)); //Random number between 0 to 1000
}
- Import the
dart:math
package using the import keyword. - Create a Random variable using the
var
keyword. - Call
nextInt()
with the maximum range. - Random numbers are always generated between 0 and the provided maximum value.
Output:
4
70
47
294
Dart Random Number Generator within a Range Example
This example generates random numbers within a specified range between the minimum and maximum values.
import 'dart:math';
main() {
var random = Random();
int min = 10;
int max = 20;
var randomNumber = min + random.nextInt(max - min);
print("$randomNumber is random number between $min and $max");
print(randomNumber);
}
Output:
19 is a random number between 10 and 20
19
How to Generate a Random Number in Dart Excluding a Particular Number?
For instance, if you wish to generate a random number between 0 and 10, excluding the number 5, you can follow this example.
import 'dart:math';
main() {
var random = Random();
var excludeNumber = 5;
var randomNumber;
do {
randomNumber = random.nextInt(10);
} while (randomNumber == excludeNumber);
print(randomNumber);
}