Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do get a random element from a List in Dart?

Tags:

dart

How can I retrieve a random element from a collection in Dart?

var list = ['a','b','c','d','e']; 
like image 661
Nik Graf Avatar asked Jul 04 '13 18:07

Nik Graf


People also ask

How do you cut a Dart List?

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.

How do you create a List in Dart?

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.


2 Answers

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)]; 
like image 192
Nik Graf Avatar answered Sep 22 '22 09:09

Nik Graf


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; 
like image 38
Jerome Puttemans Avatar answered Sep 22 '22 09:09

Jerome Puttemans