To rotate elements in a list in Dart, you can use the `rotate` method provided by the `dart:core` library.
In this example,
numbers
with integer values.rotate
method to rotate the elements by a specified distance.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int distance = 2;
numbers.rotate(distance);
print('Rotated list: \$numbers');
}
extension ListExtension<T> on List<T> {
void rotate(int distance) {
if (distance > 0) {
addAll(getRange(0, distance));
removeRange(0, distance);
} else if (distance < 0) {
insertAll(0, getRange(length + distance, length));
removeRange(length + distance, length);
}
}
}
Rotated list: [4, 5, 1, 2, 3]
In this example,
words
with string values.rotate
method to rotate the elements by a specified distance.void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
int distance = 3;
words.rotate(distance);
print('Rotated list: \$words');
}
extension ListExtension<T> on List<T> {
void rotate(int distance) {
if (distance > 0) {
addAll(getRange(0, distance));
removeRange(0, distance);
} else if (distance < 0) {
insertAll(0, getRange(length + distance, length));
removeRange(length + distance, length);
}
}
}
Rotated list: [date, elderberry, apple, banana, cherry]
In this tutorial, we learned How to Rotate Elements in a List in Dart language with well detailed examples.