如何使用Dart生成随机数?


当前回答

试试这个,你可以控制最小/最大值:

注意,您需要导入省道数学库。

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

其他回答

你可以通过在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

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

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

另一种解决方案可以使用以下代码random。这个类应该与种子一起使用。它提供了一个熟悉的。net接口,它是从mono的Random.cs移植过来的。此代码可能不是加密安全的,并且没有经过统计测试。

无法评论,因为我刚刚创建了这个帐户,但我想确保指出,@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

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

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

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