OneBite.Dev - Coding blog in a bite size

Shuffle The Elements In An Array In Dart

Code snippet for how to Shuffle The Elements In An Array In Dart with sample and detail explanation

Dart, a general-purpose programming language developed by Google, offers a number of powerful features for working with data, including arrays. In this article, we’ll be looking at how to shuffle the elements in an array in Dart.

Code snippet for Shuffling the Elements in an Array

The shuffle function can be used to randomly rearrange the elements in an array (List in Dart).

import 'dart:math';

void main() {

List<int> numbers = [1, 2, 3, 4, 5];
numbers.shuffle();

print('Shuffled numbers: $numbers');
}

Code Explanation for Shuffling the Elements in an Array

To begin, we need to import the dart:math library. This is because the shuffle function uses pseudorandom number generation (found in the dart:math package) to randomize the order of the list elements.

import 'dart:math';

Next, we create our List of integers. This will be the List that we shuffle.

List<int> numbers = [1, 2, 3, 4, 5];

Then, we can call the shuffle() function on our List. The shuffle() function is a method provided by the Dart List class and it randomly rearranges the elements of the list in place. It doesn’t return a new List; instead, it changes the original List that calls the method.

numbers.shuffle();

Finally, we print out the shuffled list. The ’$’ symbol is used in Dart to interpolate the values of the variables inside a string.

print('Shuffled numbers: $numbers');

Run the code and you will see the numbers are shuffled. Every time you run the program, you will get a different set of numbers since the shuffle operation is based on a random number generator. That’s it! You have successfully shuffled the elements in a list in Dart.

dart