A couple of examples of generating a random integer within a given range in Dart (and Flutter as well).
Example 1: Using Random().nextInt() method
The code:Advertisements
import 'dart:math';
randomGen(min, max) {
// the nextInt method generate a non-ngegative random integer from 0 (inclusive) to max (exclusive)
var x = Random().nextInt(max) + min;
// If you don't want to return an integer, just remove the floor() method
return x.floor();
}
void main() {
int a = randomGen(1, 10);
print(a);
}
Output:
8 // you may get 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
The result you get may contain min, max, or something in this range.
Example 2: Using Random.nextDouble() and floor() methods
The code:
import 'dart:math';
randomGen(min, max) {
// the nextDouble() method returns a random number between 0 (inclusive) and 1 (exclusive)
var x = Random().nextDouble() * (max - min) + min;
// If you don't want to return an integer, just remove the floor() method
return x.floor();
}
// Testing
void main() {
// with posstive min and max
print(randomGen(10, 100));
// with negative min
print(randomGen(-100, 0));
}
AdvertisementsOutput (the output, of course, is random, and will change each time you re-execute your code).
47
-69
The result you get will probably contain min but never contain max.
WhatÂ’s Next?
Continue learning more about Flutter and Dart by taking a look at the following articles:
- Dart: Convert Map to Query String and vice versa
- Sorting Lists in Dart and Flutter (5 Examples)
- 2 Ways to Create Multi-Line Strings in Dart
- How to remove items from a list in Dart
- Dart regex to validate US/CA phone numbers
You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.