如何使用Dart生成随机数?


当前回答

另一种解决方案可以使用以下代码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

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

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

一个安全的随机API刚刚添加到dart:math

new Random.secure()

飞镖:数学 Random添加了一个安全构造函数,返回加密安全的 随机发生器,从熵源提供的读取 为每个生成的随机值嵌入。

它委托给浏览器中的window.crypto.getRandomValues()和操作系统(如服务器上的urandom)

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

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

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

这对我很有用

import 'dart:math';

void main() {

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

}

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