Generate Random Number

Generate Random Number In Dart

This tutorial will teach you how to generate random numbers in dart programming. You will learn to generate random numbers between a range, and also generate a list of random numbers.

Why You Need To Generate Random Number

  • Random Number Game: You can use random numbers to create a random number game.
  • Card Game: You can use random numbers to shuffle the cards.

Example 1: Generate Random Number In Dart

This example shows how to generate random numbers from 0 - 9 and also 1 to 10. After watching this example, you can generate a random number between your choices.

import 'dart:math';
void main()
{
Random random = new Random();
int randomNumber = random.nextInt(10); // from 0 to 9 included
print("Generated Random Number Between 0 to 9: $randomNumber");
  
int randomNumber2 = random.nextInt(10)+1; // from 1 to 10 included  
print("Generated Random Number Between 1 to 10: $randomNumber2"); 
}

targets

Run Online
  • In this program, random.nextInt(10) function is used to generate a random number between 0 and 9 in which the value is stored in a variable randomNumber.

  • The random.nextInt(10)+1 function is used to generate random number between 1 to 10 in which the value is stored in a variable randomNumber2.

Generate Random Number Between Any Number

Use this formula to generate a random number between any numbers in the dart.

 min + Random().nextInt((max + 1) - min);

targets

Example 2: Random Number In Dart Between 10 - 20

This program generates random numbers between 10 to 20.

import 'dart:math';
void main()
{

int min = 10;
int max = 20; 

int randomnum = min + Random().nextInt((max + 1) - min);
  
print("Generated Random number between $min and $max is: $randomnum");  
}

targets

Run Online