— Dart, Lists, Shuffling — 1 min read
So you have a list in your Dart code, and now you want to shuffle its elements. Maybe you're building a game, implementing a feature for randomized content display, or simply need to reorganize the data. Whatever the reason, Dart makes it relatively straightforward to shuffle a list. In this article, we will dive into two different methods for shuffling a list in Dart and provide examples for each approach.
shuffle
MethodDart provides a built-in shuffle
method that's part of the List
class. This method is the simplest way to reorder the elements within a list. When called, it changes the order of elements within the original list.
Here's a basic example demonstrating the usage of the shuffle
method:
1void main() {2 var myList = [1, 2, 3, 4, 5];3 myList.shuffle();4 print(myList); // Output will be a shuffled version of the original list5}
In this example, the shuffle
method is invoked on the list myList
, resulting in a shuffled arrangement of its elements.
You can also create a custom function to shuffle a list. This approach allows you to tailor the shuffling logic according to your specific requirements.
Here's an example of a custom shuffle function in Dart:
1import 'dart:math';2
3List<T> customShuffle<T>(List<T> items) {4 var random = Random();5 for (var i = items.length - 1; i > 0; i--) {6 var j = random.nextInt(i + 1);7 var temp = items[i];8 items[i] = items[j];9 items[j] = temp;10 }11 return items;12}13
14void main() {15 var myList = [1, 2, 3, 4, 5];16 print(customShuffle(myList)); // Output will be a shuffled version of the original list17}
In this example, the customShuffle
function takes a list as input and returns a shuffled version of the original list.