flutter 获取随机数
时间: 2024-07-01 10:00:29 浏览: 7
在Flutter中,获取随机数可以使用`dart:math`库中的`Random`类。以下是一个简单的示例,展示如何生成不同类型的随机数:
1. **生成整数随机数**:
```dart
import 'dart:math';
void main() {
Random random = Random();
int randomInt = random.nextInt(100); // 生成0到99之间的整数
print('Random integer: $randomInt');
}
```
2. **生成浮点数随机数(包含小数)**:
```dart
double randomDouble = random.nextDouble(); // 生成0.0到1.0之间的浮点数
double randomInRange = random.nextDouble() * 100; // 在指定范围内,例如0.0到100.0
print('Random double: $randomDouble');
```
3. **生成随机列表或数组**:
```dart
List<int> randomList = List.generate(10, (index) => random.nextInt(10)); // 生成一个长度为10的随机整数列表
print('Random list: $randomList');
```
4. **设置种子**:
```dart
// 如果需要设置随机数的初始值(为了得到可重复的结果)
final seed = 123;
final rng = Random(seed);
```
如果你想要更高级的随机功能,如生成随机颜色、日期等,还可以结合特定库使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)