Dart List shuffle()
Syntax & Examples


Syntax of List.shuffle()

The syntax of List.shuffle() method is:

 void shuffle([Random? random]) 

This shuffle() method of List shuffles the elements of this list randomly.

Parameters

ParameterOptional/RequiredDescription
randomoptionalan optional random number generator to use for shuffling

Return Type

List.shuffle() returns value of type void.



✐ Examples

1 Shuffle a list of numbers

In this example,

  1. We create a list named numbers containing the integers [1, 2, 3, 4, 5].
  2. We then use the shuffle() method to randomly shuffle the elements of the list.
  3. We print the shuffled list to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  numbers.shuffle();
  print(numbers); // Output: Randomly shuffled list of numbers
}

Output

[3, 1, 4, 5, 2]

2 Shuffle a list of characters

In this example,

  1. We create a list named characters containing the characters ['a', 'b', 'c', 'd'].
  2. We then use the shuffle() method to randomly shuffle the elements of the list.
  3. We print the shuffled list to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd'];
  characters.shuffle();
  print(characters); // Output: Randomly shuffled list of characters
}

Output

[c, a, b, d]

3 Shuffle a list of words

In this example,

  1. We create a list named words containing the strings ['apple', 'banana', 'cherry', 'date'].
  2. We then use the shuffle() method to randomly shuffle the elements of the list.
  3. We print the shuffled list to standard output.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry', 'date'];
  words.shuffle();
  print(words); // Output: Randomly shuffled list of words
}

Output

[banana, date, apple, cherry]

Summary

In this Dart tutorial, we learned about shuffle() method of List: the syntax and few working examples with output and detailed explanation for each example.