23.3 C
New York
Wednesday, August 17, 2022

Flutter/Dart: Generate Random Numbers between Min and Max

- Advertisement -

A couple of examples of generating a random integer within a given range in Dart (and Flutter as well).

Example 1: Using Random().nextInt() method

The code:Advertisements

import 'dart:math';

randomGen(min, max) {
  // the nextInt method generate a non-ngegative random integer from 0 (inclusive) to max (exclusive)
  var x = Random().nextInt(max) + min;

  // If you don't want to return an integer, just remove the floor() method
  return x.floor();
}

void main() {
  int a = randomGen(1, 10);
  print(a);


}

Output:

8 // you may get 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

The result you get may contain min, max, or something in this range.

Example 2: Using Random.nextDouble() and floor() methods

The code:

import 'dart:math';

randomGen(min, max) {
  // the nextDouble() method returns a random number between 0 (inclusive) and 1 (exclusive)
  var x = Random().nextDouble() * (max - min) + min;

  // If you don't want to return an integer, just remove the floor() method
  return x.floor();
}

// Testing
void main() {
  // with posstive min and max
  print(randomGen(10, 100));
  
  // with negative min 
  print(randomGen(-100, 0));
}

AdvertisementsOutput (the output, of course, is random, and will change each time you re-execute your code).

47
-69

The result you get will probably contain min but never contain max.

What’s Next?

Continue learning more about Flutter and Dart by taking a look at the following articles:

You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.

Advertisements
- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles