Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 in the following code:

randomListItem(List lst) => lst[rnd.nextInt(lst.length)];

See also

  • Consult the previous recipe for more information about the use of Random