For certain applications such as games, it is necessary to have a means to retrieve a random element from a collection in Dart. This recipe will show you a simple way to do this.
This is easy to do; refer to the random_list.dart
file:
import 'dart:math'; Random rnd = new Random(); var lst = ['Bill','Joe','Jennifer','Louis','Samantha']; void main() { var element = lst[rnd.nextInt(lst.length)]; print(element); // e.g. 'Louis' element = randomListItem(lst); print(element); // e.g. 'Samantha' }
We generate a random index number based on the list length and use it to retrieve a random element from the list. If you need this often, use the one-line function randomListItem
for it, as shown in the following code:
randomListItem(List lst) => lst[rnd.nextInt(lst.length)];