如何从Dart中的集合中检索随机元素?
var list = ['a','b','c','d','e'];
Run Code Online (Sandbox Code Playgroud)
Nik*_*raf 35
import "dart:math";
var list = ['a','b','c','d','e'];
// generates a new Random object
final _random = new Random();
// generate a random index based on the list length
// and use it to retrieve the element
var element = list[_random.nextInt(list.length)];
Run Code Online (Sandbox Code Playgroud)
Raz*_*ayi 14
import "dart:math";
var list = ['a','b','c','d','e'];
list[Random().nextInt(list.length)]
Run Code Online (Sandbox Code Playgroud)
763*_*763 14
我刚刚为 List 创建了一个扩展方法。
import 'dart:math';
extension RandomListItem<T> on List<T> {
T randomItem() {
return this[Random().nextInt(length)];
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以这样使用它。
List.randomItem()
Run Code Online (Sandbox Code Playgroud)
例子 :
Scaffold(
body: SafeArea(
child: isItLogin
? Lottie.asset('assets/lottie/53888-login-icon.json')
: Lottie.asset(LottieAssets.loadingAssets.randomItem()),
),
);
Run Code Online (Sandbox Code Playgroud)
您可以使用dart_random_choice包来帮助您。
import 'package:dart_random_choice/dart_random_choice.dart';
var list = ['a','b','c','d','e'];
var el = randomChoice(list);
Run Code Online (Sandbox Code Playgroud)
这也适用:
var list = ['a','b','c','d','e'];
//this actually changes the order of all of the elements in the list
//randomly, then returns the first element of the new list
var randomItem = (list..shuffle()).first;
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想弄乱列表,请创建一个副本:
var randomItem = (list.toList()..shuffle()).first;
Run Code Online (Sandbox Code Playgroud)
var list = ['a','b','c','d','e'];
list.elementAt(Random().nextInt(list.length));
Run Code Online (Sandbox Code Playgroud)
这是由集合包的IterableExtension.sample()方法提供的:
import 'package:collection/collection.dart';
var list = ['a','b','c','d','e'];
print(list.sample(1).single);
Run Code Online (Sandbox Code Playgroud)
输出示例:
e
Run Code Online (Sandbox Code Playgroud)
请注意,该方法被推广为返回列表的N个样本。
| 归档时间: |
|
| 查看次数: |
6020 次 |
| 最近记录: |