import 'dart:math'; randomGen(min, max) { //nextInt 方法生成一个从 0(包括)到 max(不包括)的非负随机整数 var x = Random().nextInt(max) + min; //如果您不想返回整数,只需删除 floor() 方法 return x.floor(); } void main() { int a = randomGen(1, 10); print(a); }输出:
8 // you may get 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
您得到的结果可能包含最小值、最大值或此范围内的值。
import 'dart:math'; randomGen(min, max) { // nextDouble() 方法返回一个介于 0(包括)和 1(不包括)之间的随机数 var x = Random().nextDouble() * (max - min) + min; // 如果您不想返回整数,只需删除 floor() 方法 return x.floor(); } // Testing void main() { // with posstive min and max print(randomGen(10, 100)); // with negative min print(randomGen(-100, 0)); }输出(输出当然是随机的,每次重新执行代码时都会改变)。