0

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?

3
  • stackoverflow.com/questions/17476718/… Commented Jun 28, 2021 at 13:14
  • @AshKhachatryan I dont want to get just one element from list I need 12 variables to create new list Commented Jun 28, 2021 at 13:26
  • you can shuffle your array and get first 12. yourArray.shuffle() Commented Jun 29, 2021 at 8:13

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.