How do I generate random numbers in Dart?

Viewed 238892

How do I generate random numbers using Dart?

19 Answers

You can achieve it via Random class object random.nextInt(max), which is in dart:math library. The nextInt() method requires a max limit. The random number starts from 0 and the max limit itself is exclusive.

import 'dart:math';
Random random = new Random();
int randomNumber = random.nextInt(100); // from 0 upto 99 included

If you want to add the min limit, add the min limit to the result

int randomNumber = random.nextInt(90) + 10; // from 10 upto 99 included

try this, you can control the min/max value :

NOTE that you need to import dart math library.

import 'dart:math';

void main() {
  
  int random(int min, int max) {
    return min + Random().nextInt(max - min);
  }

  print(random(5, 20)); // Output : 19, 5, 15.. (5 -> 19, 20 is not included)
}

its worked for me new Random().nextInt(100); // MAX = number

it will give 0 to 99 random number

Eample::

import 'dart:math';
int MAX = 100;
print(new Random().nextInt(MAX));`

Not able to comment because I just created this account, but I wanted to make sure to point out that @eggrobot78's solution works, but it is exclusive in dart so it doesn't include the last number. If you change the last line to "r = min + rnd.nextInt(max - min + 1);", then it should include the last number as well.

Explanation:

max = 5;
min = 3;
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//max - min is 2
//nextInt is exclusive so nextInt will return 0 through 1
//3 is added so the line will give a number between 3 and 4
//if you add the "+ 1" then it will return a number between 3 and 5

Let me solve this question with a practical example in the form of a simple dice rolling app that calls 1 of 6 dice face images randomly to the screen when tapped.

first declare a variable that generates random numbers (don't forget to import dart.math). Then declare a variable that parses the initial random number within constraints between 1 and 6 as an Integer.

Both variables are static private in order to be initialized once.This is is not a huge deal but would be good practice if you had to initialize a whole bunch of random numbers.

static var _random = new Random();
static var _diceface = _random.nextInt(6) +1 ;

Now create a Gesture detection widget with a ClipRRect as a child to return one of the six dice face images to the screen when tapped.

GestureDetector(
          onTap: () {
            setState(() {
              _diceface = _random.nextInt(6) +1 ;
            });
          },
          child: ClipRRect(
            clipBehavior: Clip.hardEdge,
            borderRadius: BorderRadius.circular(100.8),
              child: Image(
                image: AssetImage('images/diceface$_diceface.png'),
                fit: BoxFit.cover,
              ),
          )
        ),

A new random number is generated each time you tap the screen and that number is referenced to select which dice face image is chosen.

I hoped this example helped :)

Dice rolling app using random numbers in dart

you can generate by simply in this way there is a class named Random();

you can use that and genrate random numbers

Random objectname = Random();
int number = objectname.nextInt(100);
// it will generate random number within 100.

For me the easiest way is to do:

import 'dart:math';
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//where min and max should be specified.

Thanks to @adam-singer explanation in here.

Use Dart Generators, that is used to produce a sequence of number or values.

 main(){ 
       print("Sequence Number");
       oddnum(10).forEach(print);
     }
    Iterable<int> oddnum(int num) sync*{
     int k=num;
     while(k>=0){
       if(k%2==1){
        yield k;
       }
      k--;
     } 
}

Use class Random() from 'dart:math' library.

import 'dart:math';

void main() {
  int max = 10;
  int RandomNumber = Random().nextInt(max);
  print(RandomNumber);
}

This should generate and print a random number from 0 to 9.

This method generates random integer. Both minimum and maximum are inclusive.

Make sure you add this line to your file: import 'dart:math'; Then you can add and use this method:

int randomInt(int min, int max) {
return Random().nextInt(max - min + 1) + min;
}

So if you call randomInt(-10,10) it will return a number between -10 and 10 (including -10 and 10).

one line solution you can directly call all the functions with constructor as well.

import 'dart:math';

print(Random().nextInt(100));
Related