By Alvin Alexander. Last updated: July 1, 2021
If you need to get a random element from a list in Dart, I can confirm this this getRandomListElement
method works:
import "dart:math";
T getRandomElement<T>(List<T> list) {final random = new Random(); var i = random.nextInt(list.length); return list[i]; }
You can test it in Dartpad with this main
method:
void main() {
var list = ['a','b','c'];
var element = getRandomElement(list);
print(element);
}
Because the random element function uses a generic type, you can also use it with lists of other types, such as this list of integers:
void main() {
var list = [1, 2, 3];
var element = getRandomElement(list);
print(element);
}
In summary, if you need a Dart function that returns a random element from a list, I hope this function is helpful.