如何从颤振中的数组中获取随机变量

时间:2021-06-28 13:06:16

标签: arrays flutter arraylist random

我是 Flutter 的新手。我有一个字符串数组,它有 20 个值。但是,我想从这个数组中取出 12 个随机值并用这个值创建一个新数组。你能给我指路吗?

1 个答案:

答案 0 :(得分:1)

适应this question

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

//adjust to you with 12
for (int i = 0; i < 3; i++) {
  // 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
  int index = _random.nextInt(list.length);
  var element = list[index];

  //add the element to your new list and remove it to the old list
  newList.add(element);
  list.removeAt(index);
}
print(newList);