how to generate random number in dart
generate random number in dart

Hi Guys, Welcome to Proto Coders Point.

In this dart tutorial (article), we will learn how to generate random number in dart.

In Dart programming, A Random number are often used in flutter application where a user can generate a unique key number.

What is Random Number in dart program?

In dart, A Random Number is a randomly generated from a large set of numbers & select a number using some mathematical algorithm.

Generating random number are commonly implemented in many flutter application having a feature like OTP verification for user SignIn.

One of the best example where dart random number in range is implemented is dice game, whenever a dice is thrown we get a fixed range of random number ranging between 1 – 6.

Dart Random class – In math package

In dart, we have a class named “Random” which is used to generate random integer number, bool , random decimal number.

Note: To use Random class in dart, we must import ‘dart:math’ packagem because Random Class is defined in dart:math package.

It can generate random booleon, integer and double value by using its method provided.

Method on Math.random class

MethodDescription
nextBool() =>Generate either true or false randomly.
nextDouble() => Generate an positive floating point number ranging from 0.0 to 1.0.
nextInt(int max) => Generate a positive number range from 0 to max(as defined)
Eg: random.nextInt(6); // Here 6 is a range, number will generate from 0 – 6.

Dart Porgram to generate random number bool, int, double

1. Dart Program random number

import 'dart:math';

void main() {
  var random = new Random();

   print(random.nextBool()); //true or false

   print(random.nextInt(75)); // number between 0 - 75

   print(random.nextDouble());  // double value 0.0 to 1.0

}
dart random number output

2. How to generate fixed digit number

Eg: Generate a fixed 5 digit or 6 digit random number.

import 'dart:math';

void main() {
   Generate5digit();
}

Generate5digit(){
     var rng = new Random();
     var rand = rng.nextInt(90000) + 10000;
     print(rand.toInt());
}

So in above dart code, you can get a random number in range 00000 to 90000 and add 10000 to it. you always get a 5 digit random number generated.

5 digit random number dart

3. How to get dart random number between range. Eg : 50 – 100

import 'dart:math';

void main() {
  var random = new Random();
  print(''); //just for next line space in output

  print(' Random Number from 0 - 50 :  ${next(0, 50,random)}');

  print('');
}


int next(int min, int max,Random rand) => min + rand.nextInt(max - min);
dart random number between range


How to Generate OTP number in flutter