Ad

How Can I Take Random Variables From Array In Flutter

- 1 answer

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?

Ad

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);
Ad
source: stackoverflow.com
Ad