Flutter/Dart: How to generate random numbers between min and max

July 2, 2020 Linda Walker Loading... Post a comment

The code snippet below shows you how to generate a random integer between a min and a max numbers.

import 'dart:math';

randomGen(min, max){
  var random = Random();
  
  // the nextDouble() method returns a random number between 0 and 1
  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));
}

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

47
-69
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles

0
Would love your thoughts, please comment.x
()
x