How can I retrieve a random element from a collection in Dart?
var list = ['a','b','c','d','e'];
In Dart, we use the List. sublist( ) method to slice a list. This method takes the starting index as the first argument and the ending index as the second argument and returns a List of sliced items. If you don't pass the second argument then List.
Using addAll() method to add all the elements of another list to the existing list. Creating a new list by adding two or more lists using addAll() method of the list. Creating a new list by adding two or more list using expand() method of the list. Using + operator to combine list.
import "dart:math"; var list = ['a','b','c','d','e']; // 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 var element = list[_random.nextInt(list.length)];
This works too:
var list = ['a','b','c','d','e']; //this actually changes the order of all of the elements in the list //randomly, then returns the first element of the new list var randomItem = (list..shuffle()).first;
or if you don't want to mess the list, create a copy:
var randomItem = (list.toList()..shuffle()).first;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With