60

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

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

5 回答 5

122
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)];
于 2013-07-04T18:58:57.587 回答
62

这也有效:

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;
于 2018-02-09T09:54:54.263 回答
20
import "dart:math";

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

list[Random().nextInt(list.length)]
于 2020-04-06T10:14:26.780 回答
10

您可以使用dart_random_choice包来帮助您。

import 'package:dart_random_choice/dart_random_choice.dart';

var list = ['a','b','c','d','e'];
var el = randomChoice(list);
于 2019-04-13T00:11:36.593 回答
6

我刚刚为 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()),
      ),
    );
于 2021-05-12T17:02:15.520 回答