如何得到一个随机元素从一个列表在 Dart?

如何在 Dart 中从集合中检索随机元素?

var list = ['a','b','c','d','e'];
51383 次浏览
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 'package:dart_random_choice/dart_random_choice.dart';


var list = ['a','b','c','d','e'];
var el = randomChoice(list);
import "dart:math";


var list = ['a','b','c','d','e'];


list[Random().nextInt(list.length)]

我刚刚为 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()),
),
);
var list = ['a','b','c','d','e'];
list.elementAt(Random().nextInt(list.length));