如何从 Dart 的集合中检索随机元素?
var list = ['a','b','c','d','e'];
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)];
这也有效:
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;
或者如果您不想弄乱列表,请创建一个副本:
var randomItem = (list.toList()..shuffle()).first;
import "dart:math";
var list = ['a','b','c','d','e'];
list[Random().nextInt(list.length)]
您可以使用dart_random_choice包来帮助您。
import 'package:dart_random_choice/dart_random_choice.dart';
var list = ['a','b','c','d','e'];
var el = randomChoice(list);
我刚刚为 List 创建了一个扩展方法。
import 'dart:math';
extension RandomListItem<T> on List<T> {
T randomItem() {
return this[Random().nextInt(length)];
}
}
我们可以这样使用它。
List.randomItem()
例子 :
Scaffold(
body: SafeArea(
child: isItLogin
? Lottie.asset('assets/lottie/53888-login-icon.json')
: Lottie.asset(LottieAssets.loadingAssets.randomItem()),
),
);