如何使用Dart生成随机数?


当前回答

您可以简单地用这种方式生成 有一个名为Random()的类;

你可以用它来生成随机数

Random objectname = Random();
int number = objectname.nextInt(100);
// it will generate random number within 100.

其他回答

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

import 'dart:math';

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

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

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

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

这对我很有用

import 'dart:math';

void main() {

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

}

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

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