In this post, we will learn to generate various kinds of random values in Dart for your Flutter application. As a bonus, we will cover generating a random number including both positive and negative numbers.
Introduction
Often we need to work with random values in our application. Maybe we need to generate a random number to get a random item from a list. Or maybe we want to get a random decimal value. These are quite common scenarios. So how can we get these random values?
We can use the Random
class which resides in the dart:math
library for this purpose. Let’s play around with some examples.
Getting Random Values With Random Class In Dart
First create an instance of Random
object.
import 'dart:math';
void main() {
var randomGenerator = Random();
}
Now we can use the randomGenerator
for generating random values.

As shown above, we get various method options to generate random values.
Generating A Random Integer Number In Dart
Use the nextInt
function to generate a random number. The max
parameter allows to set the restriction for maximum allowed valid value when generating the random number.
randomGenerator.nextInt(10);
The code above will generate a random number from 0 to 10.
Note: The maximum value is not included in the results but minimum is included.
Generating A Random Decimal Value
Similar to integer values, we can also generate random decimal values with the Random
class object.
randomGenerator.nextDouble();
Unlike nextInt
method, the nextDouble
method doesn’t take any parameters. The results range from 0.0 to 1.0 with 1.0 being exclusive.
Generating A Random Boolean Value
Finally, we can use the nextBool
method to generate a random boolean value in Dart.
randomGenerator.nextBool();
Bonus
Generating A Random Positive Or Negative Number In Dart
As you might have noticed, the Random
class doesn’t have a direct implementation for generating a random number that includes a negative number. However, we can achieve generating a random that includes negative numbers in the following way:
int _generateRandomIncludingNegative(int max) {
var randomGenerator = Random();
var positive = randomGenerator.nextBool();
var randInt = randomGenerator.nextInt(max);
var result = positive ? randInt : 0 - randInt;
return result;
}
The function _generateRandomIncludingNegative
uses the combination of nextBool
and nextInt
to generate a random number including both positive and negative number. The number ranges from negative max to positve max.
For example the code below will return values from -5 to 5 excluding both -5 and 5.
print(_generateRandomIncludingNegative(5));
You must be logged in to post a comment.