I am new to flutter. I have one String Array and it has 20 values. However, I want to take 12 random values from this array and create a new array with this values. Can you show me the way?
-
stackoverflow.com/questions/17476718/…Ash Khachatryan– Ash Khachatryan2021-06-28 13:14:01 +00:00Commented Jun 28, 2021 at 13:14
-
@AshKhachatryan I dont want to get just one element from list I need 12 variables to create new listsalih suat kükrer– salih suat kükrer2021-06-28 13:26:56 +00:00Commented Jun 28, 2021 at 13:26
-
you can shuffle your array and get first 12. yourArray.shuffle()Ash Khachatryan– Ash Khachatryan2021-06-29 08:13:05 +00:00Commented Jun 29, 2021 at 8:13
Add a comment
|
1 Answer
Adapted to 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);