O'Reilly logo

Dart: Scalable Application Development by Ivo Balbaert, Sergey Akopkokhyants, Davy Mitchell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting a random element from a list

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.

How to do it...

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'
}

How it works...

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required