To reverse a list in Dart, you can use the reversed
property or implement a custom reverse method using nested loops.
In this example,
numbers
with integer values.reversed
property to get an iterable with elements in reverse order.toList
method.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
List<int> reversedNumbers = numbers.reversed.toList();
print('Reversed list: \$reversedNumbers');
}
Reversed list: [5, 4, 3, 2, 1]
In this example,
numbers
with integer values.reverseList
that takes a list as input.reverseList
, we use a nested loop where the outer loop iterates from the start to the middle of the list, and the inner loop performs the element swap.i
and the inner loop index j
represent the positions of elements to be swapped.i
and j
until the loop reaches the middle of the list.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
reverseList(numbers);
print('Reversed list: \$numbers');
}
void reverseList(List<int> list) {
int count = list.length;
for (int i = 0; i < count ~/ 2; i++) {
int temp = list[i];
list[i] = list[count - i - 1];
list[count - i - 1] = temp;
}
}
Reversed list: [5, 4, 3, 2, 1]
In this tutorial, we learned How to Reverse a List in Dart language with well detailed examples.