Random numbers
suggest changeIn Dart, random numbers are generated using the Random class from the dart:math core library. It supports generating pseudo-random integers, floating-point numbers, booleans, and cryptographically secure random values.
Basic Usage with Random
Import dart:math and instantiate Random:
import 'dart:math';
void main() {
final random = Random();
// Random integer between 0 (inclusive) and max (exclusive)
int randomInt = random.nextInt(100); // 0 to 99
print('Random int (0-99): $randomInt');
// Random double between 0.0 (inclusive) and 1.0 (exclusive)
double randomDouble = random.nextDouble();
print('Random double: $randomDouble');
// Random boolean
bool randomBool = random.nextBool();
print('Random bool: $randomBool');
}
Generating Numbers Within a Range
To generate an integer within an arbitrary range [min, max] (inclusive):
import 'dart:math';
int randomInRange(Random random, int min, int max) {
return min + random.nextInt(max - min + 1);
}
void main() {
final random = Random();
int diceRoll = randomInRange(random, 1, 6);
print('Dice roll: $diceRoll');
}
Cryptographically Secure Random Numbers
For security-sensitive operations (such as generating session tokens, encryption keys, or password salts), use Random.secure(). It relies on the operating system's CSPRNG (Cryptographically Secure Pseudo-Random Number Generator):
import 'dart:convert';
import 'dart:math';
String generateSecureToken([int length = 32]) {
final secureRandom = Random.secure();
final values = List<int>.generate(length, (_) => secureRandom.nextInt(256));
return base64Url.encode(values);
}
void main() {
String token = generateSecureToken();
print('Secure token: $token');
}
Reproducible Sequences with Seeds
You can pass an integer seed to Random(seed). Supplying the same seed produces the exact same sequence of numbers, which is useful for deterministic testing and procedural generation:
import 'dart:math';
void main() {
final rng1 = Random(42);
final rng2 = Random(42);
// Both generators will produce identical results
print(rng1.nextInt(1000) == rng2.nextInt(1000)); // true
}
Shuffling and Picking Random Elements
Dart's List provides a built-in shuffle() method that accepts an optional Random generator:
import 'dart:math';
void main() {
final random = Random();
final colors = ['red', 'green', 'blue', 'yellow', 'purple'];
// Pick a single random element
final randomColor = colors[random.nextInt(colors.length)];
print('Selected color: $randomColor');
// Shuffle the list in-place
colors.shuffle(random);
print('Shuffled colors: $colors');
}