Dart/Flutter - Generate Random Number Examples

This tutorial shows you how to generate a random number (integer or float) in Dart within a specified range.

If your Dart application has a logic that requires random number generation, it can be done easily and doesn't require any additional dependency. Dart already has the functionality for generating random numbers that's uniformly distributed. You can read the example below which also works in any Dart framework including Flutter.

Using Dart Random Class

Dart has a class named Random which is available to use by importing dart:math. The class has two factory constructors as shown below. The latter is suitable for generating cryptographically secure random numbers.

  factory Random([int? seed]);
  factory Random.secure();

First, you need to get the instance of the Random class.

  Random random = Random();
  Random random = Random.secure();

After that, you can call the methods of the class. The examples are shown below.

Generate Random Integer Between a Range

The Random class has a method named nextInt which generates a positive random integer from 0 (inclusive) to the value passed as max argument (exclusive).

  int nextInt(int max);

In the example below, Dart will generate a random integer from 0 to 9. The max value (10) is exclusive, so the biggest integer that can be generated is 9.

  int randomNumber = random.nextInt(10);

If you want to generate a random integer not starting from 0, you can do a little trick. Basically, the value passed to the nextInt method represents the generation range. Therefore, you can pass the maximum value subtracted by the minimum value to the nextInt method. Then, add the minimum value to the result, so that the generated values will not start from 0.

  int generateRandomInt(int min, int max) =>
      Random().nextInt(max - min) + min;

Generate Random Double Between a Range

To generate a random double value, you can use the nextDouble method. It generates a positive random floating point value from 0.0 (inclusive) to 1.0 (exclusive).

  double nextDouble();

Below is the usage example which generates a floating point value with a minimum value of 0.0 and a maximum value less than 1.0.

  random.nextDouble()

If you want to generate a double value with a different range, just multiply the result with the generation range, which is the maximum value subtracted by the minimum value. Then, add the minimum value to the result.

  double generateRandomDouble(num min, num max) =>
      random.nextDouble() * (max - min) + min;

Summary

Dart's Random class already has the functionality to generate random numbers. You can use nextInt or nextDouble to generate a random integer or double respectively. If the value to be generated must be within a range, just multiply the result of nextInt or nextDouble with the generation range and add the minimum value to the result.

You can also read about: