How do I generate random numbers using Dart?
use this library http://dart.googlecode.com/svn/branches/bleeding_edge/dart/lib/math/random.dart provided a good random generator which i think will be included in the sdk soon hope it helps
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
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--;
}
}
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
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.
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)