flutter如何生成随机数

在Flutter中如何生成随机数?有没有简单的代码示例可以参考?例如生成指定范围内的整数或浮点数?使用什么类库或方法比较推荐?

2 回复

在Flutter中生成随机数,使用dart:math库的Random类。示例代码:

import 'dart:math';
void main() {
  var random = Random();
  print(random.nextInt(100)); // 生成0-99的随机整数
}

也可用random.nextDouble()生成0.0-1.0的随机小数。

更多关于flutter如何生成随机数的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中生成随机数可以使用 Dart 语言的 dart:math 库中的 Random 类。以下是具体方法:

  1. 导入库

    import 'dart:math';
    
  2. 生成随机数

    • 随机整数:使用 nextInt(max),生成 0 到 max-1 之间的整数。
      Random random = Random();
      int randomNumber = random.nextInt(100); // 生成 0 到 99 的随机整数
      
    • 随机浮点数:使用 nextDouble(),生成 0.0 到 1.0 之间的浮点数。
      double randomDouble = random.nextDouble(); // 生成 0.0 到 1.0 的随机浮点数
      
    • 随机布尔值:使用 nextBool()
      bool randomBool = random.nextBool(); // 随机 true 或 false
      
  3. 指定范围随机数

    • 生成 minmax 的随机整数:
      int randomInRange(int min, int max) {
        return min + Random().nextInt(max - min + 1);
      }
      // 示例:生成 5 到 15 的随机整数
      int num = randomInRange(5, 15);
      

注意事项

  • 默认使用 Random() 构造函数,它会自动生成随机种子。
  • 如需可重复的随机序列,可使用 Random(seed) 指定种子。

示例完整代码:

import 'dart:math';

void main() {
  Random random = Random();
  
  print('随机整数: ${random.nextInt(50)}'); // 0-49
  print('随机浮点数: ${random.nextDouble()}'); // 0.0-1.0
  print('随机布尔值: ${random.nextBool()}');
  
  // 自定义范围
  int customRandom = randomInRange(10, 20);
  print('10到20的随机数: $customRandom');
}

int randomInRange(int min, int max) {
  return min + Random().nextInt(max - min + 1);
}

这种方法简单高效,适用于大多数 Flutter 应用场景。

回到顶部