我是 Flutter 的新手。我有一个字符串数组,它有 20 个值。但是,我想从这个数组中取出 12 个随机值并用这个值创建一个新数组。你能给我指路吗?
答案 0 :(得分:1)
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);