How to shuffle a dart list

How to shuffle a dart list:

Dart provides one method called shuffle() that can be used to shuffle the elements of the list randomly. This method is defined as below:

void shuffle([Random? random]);

This method can be used to shuffle a list. Also, we can pass one random object to this method optionally. Let me show you how:

Example to shuffle a dart list:

Let’s take a look at the example below:

void main() {
  var givenList = [1, 2, 3, 4, 5, 6, 7, 8];

  print(givenList);
  givenList.shuffle();
  
  print(givenList);
}

It shuffles the givenList. If you run it, it will print output something like below:

[1, 2, 3, 4, 5, 6, 7, 8]
[1, 7, 5, 6, 2, 4, 8, 3]

Example of shuffling by passing a random object:

We can also pass one Random object to the shuffle method like below:

import 'dart:math';
void main() {
  var givenList = [1, 2, 3, 4, 5, 6, 7, 8];

  print(givenList);
  givenList.shuffle(Random());
  
  print(givenList);
}

It will print one random list each time you run this program.

You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊