How to Reverse/Shuffle a List in Dart

Last updated on July 4, 2022 A Goodman Loading... Post a comment

The two examples below show you how to reverse and shuffle a given list in Dart.

Reversing a Dart list

The code:

// main.dart
void main() {
  final List listOne = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  final List listTwo = ['a', 'b', 'c', 'd'];

  final List reversedListOne = listOne.reversed.toList();
  print(reversedListOne);

  final List reversedListTwo = listTwo.reversed.toList();
  print(reversedListTwo);
}

Output:

[9, 8, 7, 6, 5, 4, 3, 2, 1]
[d, c, b, a]

Shuffling a Dart list

We can shuffle a list randomly by using the shuffle() method. Note that this method will change the original list.

Example:

// main.dart
void main() {
  final List listOne = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  final List listTwo = ['a', 'b', 'c', 'd'];

  listOne.shuffle();
  listTwo.shuffle();

  print(listOne);
  print(listTwo);
}

Output:

[5, 1, 9, 4, 2, 3, 7, 8, 6]
[b, c, a, d]

Due to the randomness, you are very likely to receive a different output each time you execute the code.

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like