The syntax of List.shuffle() method is:
void shuffle([Random? random])
This shuffle() method of List shuffles the elements of this list randomly.
Parameter | Optional/Required | Description |
---|---|---|
random | optional | an optional random number generator to use for shuffling |
List.shuffle() returns value of type void
.
In this example,
numbers
containing the integers [1, 2, 3, 4, 5]
.shuffle()
method to randomly shuffle the elements of the list.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
numbers.shuffle();
print(numbers); // Output: Randomly shuffled list of numbers
}
[3, 1, 4, 5, 2]
In this example,
characters
containing the characters ['a', 'b', 'c', 'd']
.shuffle()
method to randomly shuffle the elements of the list.void main() {
List<String> characters = ['a', 'b', 'c', 'd'];
characters.shuffle();
print(characters); // Output: Randomly shuffled list of characters
}
[c, a, b, d]
In this example,
words
containing the strings ['apple', 'banana', 'cherry', 'date']
.shuffle()
method to randomly shuffle the elements of the list.void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date'];
words.shuffle();
print(words); // Output: Randomly shuffled list of words
}
[banana, date, apple, cherry]
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.