Reputation: 120439
How do I generate random numbers using Dart?
Upvotes: 347
Views: 344612
Reputation: 81
Generating random number in a specific range using Random() class:
If you just want to limit it from the top
var intValue = Random().nextInt(10); // Value is >= 0 and < 10.
Or if you want to limit it from bottom also, just add your lowest number, for ex:
intValue = Random().nextInt(100) + 50; // Value is >= 50 and < 150.
Upvotes: 1
Reputation: 464
You could use this code, to generate a random number with N digits:
import 'dart:math';
int random_with_N_digits(int n) {
final start = pow(10, (n - 1));
final end = pow(10, n) - 1;
Random random = Random();
final x = random.nextInt(end.toInt()) + start;
return x.toInt();
}
this code converted from Python code.
Upvotes: 0
Reputation: 120439
Use Random
class from dart:math
:
import 'dart:math';
void main() {
var rng = Random();
for (var i = 0; i < 10; i++) {
print(rng.nextInt(100));
}
}
This code was tested with the Dart VM and dart2js, as of the time of this writing.
Upvotes: 424
Reputation: 6367
To generate random double:
import 'dart:math';
print(Random().nextDouble());
Upvotes: 2
Reputation: 649
This works for me
import 'dart:math';
void main() {
Random random = Random();
int randomNumber = random.nextInt(5) + 1;
print(randomNumber);
}
Change the number five for possible results you want
Upvotes: 2
Reputation: 91
Let me answer 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.
Dice rolling app using random numbers in dart
Upvotes: 9
Reputation: 954
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)
}
Upvotes: 47
Reputation: 126
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).
Upvotes: 3
Reputation: 129
one line solution you can directly call all the functions with constructor as well.
import 'dart:math';
print(Random().nextInt(100));
Upvotes: 2
Reputation: 852
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.
Upvotes: 6
Reputation: 21
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.
Upvotes: 2
Reputation: 23
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--;
}
}
Upvotes: 2
Reputation: 2880
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
Upvotes: 167
Reputation: 3700
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));`
Upvotes: 8
Reputation: 81
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
Upvotes: 8
Reputation: 2091
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.
Upvotes: 3
Reputation: 26871
Here's a snippet for generating a list of random numbers
import 'dart:math';
main() {
var rng = new Random();
var l = new List.generate(12, (_) => rng.nextInt(100));
}
This will generate a list of 12 integers from 0 to 99 (inclusive).
Upvotes: 31
Reputation: 657018
A secure random API was just added to dart:math
new Random.secure()
dart:math
Random
added asecure
constructor returning a cryptographically secure random generator which reads from the entropy source provided by the embedder for every generated random value.
which delegates to window.crypto.getRandomValues()
in the browser and to the OS (like urandom
on the server)
Upvotes: 27
Reputation: 3941
Just wrote this little class for generating Normal Random numbers... it was a decent starting point for the checking I need to do. (These sets will distribute on a "bell" shaped curve.) The seed will be set randomly, but if you want to be able to re-generate a set you can just pass some specific seed and the same set will generate.
Have fun...
class RandomNormal {
num _min, _max, _sum;
int _nEle, _seed, _hLim;
Random _random;
List _rNAr;
//getter
List get randomNumberAr => _rNAr;
num _randomN() {
int r0 = _random.nextInt(_hLim);
int r1 = _random.nextInt(_hLim);
int r2 = _random.nextInt(_hLim);
int r3 = _random.nextInt(_hLim);
num rslt = _min + (r0 + r1 + r2 + r3) / 4000.0; //Add the OS back in...
_sum += rslt; //#DEBUG ONLY
return( rslt );
}
RandomNormal(this._nEle, this._min, this._max, [this._seed = null]) {
if (_seed == null ) {
Random r = new Random();
_seed = r.nextInt(1000);
}
_hLim = (_max - _min).ceil() * 1000;
_random = new Random(_seed);
_rNAr = [];
_sum = 0;//#DEBUG ONLY
h2("RandomNormal with k: ${_nEle}, Seed: ${_seed}, Min: ${_min}, Max: ${_max}");//#DEBUG ONLY
for(int n = 0; n < _nEle; n++ ){
num randomN = _randomN();
//p("randomN = ${randomN}");
LIST_add( _rNAr, randomN );
}
h3("Mean = ${_sum/_nEle}");//#DEBUG ONLY
}
}
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
new RandomNormal(1000, 80, 120);
Then you can just use it like this to check the mean of sets of 1000 nums generated between a low and high limit. The values are stored in the class so they can be accessed after instantiation.
_swarmii
Upvotes: 3
Reputation: 4837
An alternative solution could be using the following code DRandom. This class should be used with a seed. It provides a familiar interface to what you would expect in .NET, it was ported from mono's Random.cs. This code may not be cryptography safe and has not been statistically tested.
Upvotes: 3
Reputation: 654
If you need cryptographically-secure random numbers (e.g. for encryption), and you're in a browser, you can use the DOM cryptography API:
int random() {
final ary = new Int32Array(1);
window.crypto.getRandomValues(ary);
return ary[0];
}
This works in Dartium, Chrome, and Firefox, but likely not in other browsers as this is an experimental API.
Upvotes: 19