如何使用Dart生成随机数?
如何使用Dart生成随机数?
使用dart:math
中的Random
类:
import 'dart:math';
void main() {
var rng = Random();
for (var i = 0; i < 10; i++) {
print(rng.nextInt(100));
}
}
此代码已在编写本文时使用Dart VM和dart2js进行测试。
File
类读取/dev/urandom
。 - Towernew Random.secure()
可以生成密码学强度的随机数。 - Sisir你可以通过Random
类对象random.nextInt(max)
来实现,该类在dart:math
库中。其中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
尝试这个,你可以控制最小/最大值:
注意需要导入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)
}
这里是生成随机数列表的代码片段:
import 'dart:math';
main() {
var rng = new Random();
var l = new List.generate(12, (_) => rng.nextInt(100));
}
这将生成一个包含0到99(包括)的12个整数的列表。
在 dart:math
中刚刚添加了一个安全的随机 API。
new Random.secure()
dart:math
Random
新增了一个secure
构造函数,返回一个加密安全的随机生成器,它为每个生成的随机值读取由嵌入程序提供的熵源。
在浏览器中委托给window.crypto.getRandomValues()
,在服务器上则委托给操作系统(例如urandom
)
如果你需要密码学安全的随机数(例如用于加密),并且你正在使用浏览器,你可以使用DOM加密API:
int random() {
final ary = new Int32Array(1);
window.crypto.getRandomValues(ary);
return ary[0];
}
这在Dartium、Chrome和Firefox中可以工作,但由于这是实验性API,很可能无法在其他浏览器中工作。
static var _random = new Random();
static var _diceface = _random.nextInt(6) +1 ;
GestureDetector(
onTap: () {
setState(() {
_diceface = _random.nextInt(6) +1 ;
});
},
child: ClipRRect(
clipBehavior: Clip.hardEdge,
borderRadius: BorderRadius.circular(100.8),
child: Image(
image: AssetImage('images/diceface$_diceface.png'),
fit: BoxFit.cover,
),
)
),
这对我很有用 new Random().nextInt(100); // MAX = 数字
它会给出0到99之间的随机数。
例如:
import 'dart:math';
int MAX = 100;
print(new Random().nextInt(MAX));`
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
您可以通过以下简单方式生成:
有一个名为Random()的类;
您可以使用它来生成随机数。
Random objectname = Random();
int number = objectname.nextInt(100);
// it will generate random number within 100.