How to Generate a Random Boolean with Probability in Flutter

Flutter Jul 14, 2023

In Flutter, there are times when you may need to generate a random boolean value, but with a certain probability of it being true. By default, the Random class provides an equal chance of generating true or false. However, what if you want to control the occurrence of true with a specific probability, such as 90%? In this tutorial, we will explore how to generate a random boolean with a specific probability in Flutter.

Generate a random Boolean

In order to generate a random boolean in Flutter we can use the Random class of the dart:math library.

import 'dart:math';

void main() {
  Random random = Random();
  bool randomBoolean = random.nextBool();

  print(randomBoolean);
}

In this code snippet, we create a random boolean by creating an instance of the Random class. On this instance, we call the nextBool function to generate a random boolean.

Generate a Random Boolean with a Specific Probability

If we want to generate a random boolean with a specific probability let us say 90%, we can use the nextDouble function of the Random class.

import 'dart:math';

void main() {
  Random random = Random();
  bool randomBoolean = random.nextDouble() <= 0.9;

  print(randomBoolean);
}

In this code snippet, we again create an instance of the Random class. On this instance, we call the nextDouble function. This function generates a random value between 0 and 1. Every time the generated double is smaller or equal to 0.9 we return true. Otherwise, we return false.

Conclusion

Generating a random boolean value with a specific probability can be helpful in different situations while developing a Flutter application. You can achieve this by using the Random class from the dart:math library and creating a function that compares the generated random value with your desired probability. This allows you to generate random booleans based on your specific requirements.

Tags