如何使用Dart生成随机数?


当前回答

这对我很有用

import 'dart:math';

void main() {

  Random random = Random();
  int randomNumber = random.nextInt(5) + 1;
  print(randomNumber);

}

把数字5换成你想要的结果

其他回答

使用'dart:math'库中的类Random()。

import 'dart:math';

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

这将生成并打印一个从0到9的随机数。

如果你需要加密安全的随机数(例如加密),并且你在浏览器中,你可以使用DOM加密API:

int random() {
  final ary = new Int32Array(1);
  window.crypto.getRandomValues(ary);
  return ary[0];
}

这适用于Dartium、Chrome和Firefox,但可能不适用于其他浏览器,因为这是一个实验性的API。

使用省道发生器,用于产生数字或值的序列。

 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--;
     } 
}

你可以通过在dart:math库中的随机类对象Random . nextint (max)来实现它。nextInt()方法需要一个最大限制。随机数从0开始,最大限制本身是排他的。

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

如果要添加最小限制,请将最小限制添加到结果中

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

无法评论,因为我刚刚创建了这个帐户,但我想确保指出,@eggrobot78的解决方案是有效的,但它在dart中是独占的,所以它不包括最后一个数字。如果您将最后一行更改为“r = min + rnd.”nextInt(max - min + 1);”,那么它也应该包括最后一个数字。

解释:

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