flutter如何生成随机数字

在Flutter开发中,我需要生成一个指定范围内的随机整数(比如1-100),但发现dart:math的Random类每次生成的序列都相同。请问如何确保每次运行应用时都能获得不同的随机数序列?是否需要用种子初始化Random?有没有更简便的实现方式?

2 回复

在Flutter中生成随机数字,使用dart:math库的Random类。

示例代码:

import 'dart:math';

void main() {
  var random = Random();
  int randomNumber = random.nextInt(100); // 生成0-99的随机整数
  print(randomNumber);
}

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


在 Flutter 中生成随机数字,可以使用 Dart 语言内置的 Random 类。以下是具体方法:

  1. 导入库

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

    Random random = Random();
    int randomInt = random.nextInt(100); // 生成 0 到 99 之间的随机整数
    
  3. 生成随机双精度浮点数

    double randomDouble = random.nextDouble(); // 生成 0.0 到 1.0 之间的随机小数
    
  4. 生成指定范围的随机数(例如 10 到 50):

    int min = 10;
    int max = 50;
    int rangeRandom = min + random.nextInt(max - min + 1);
    

完整示例

import 'dart:math';

void main() {
  Random random = Random();
  
  print('随机整数: ${random.nextInt(100)}');
  print('随机小数: ${random.nextDouble()}');
  print('范围随机数: ${10 + random.nextInt(41)}'); // 10 到 50
}

注意事项

  • 默认使用当前时间作为随机种子
  • 如需可重复的随机序列,可使用 Random(seed)
  • 适用于简单的随机需求,加密场景请使用 Random.secure()
回到顶部