How to reverse a list in dart:
To revese a list in Dart, we have one inbuilt property called reversed. This property returns one iterable of the items in the list in reversed order. We can convert the iterable to a list using toList method.
Below is the definition of reversed :
Iterable<E> get reversed;
Example of reversing a list in Dart:
Let’s check how this property works :
void main() {
var list = new List();
list.add(1);
list.add(2);
list.add(3);
print(list);
var reversed = list.reversed;
print(reversed.toList());
}
If you run this Dart program, it will print the below output:
[1, 2, 3]
[3, 2, 1]
As you can see here, the list is reversed.
Doing inplace reverse:
The above example created one new list. We can also do inplace reversing i.e. we can modify the original list without creating a new list. For that, we need one loop to iterate through the values and reverse them during iteration.
For example, consider the below list :
[1, 2, 3, 4, 5, 6, 7]
For inplace reverse,
- We need to swap the element in position 0 with the element in position 6
- Swap element in position 1 with element in position 5
- i.e. swap element in position i with element in size - i - 1
- We don’t need any swapping for element in position 3
So, for an even sized list or odd sized list, we can run one loop and swap all elements in ith position with the elements in size - i - 1th position.
Dart program:
void main() {
var list = new List();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
print(list);
for (var i = 0; i < list.length / 2; i++) {
var tempValue = list[i];
list[i] = list[list.length - 1 - i];
list[list.length - 1 - i] = tempValue;
}
print(list);
}
Output:
The above program will print the below output:
[1, 2, 3, 4, 5, 6, 7]
[7, 6, 5, 4, 3, 2, 1]
It modifies the original list.
You might also like:
- Dart check for any or every element in a list satisfy a given condition
- Dart program to check if a list contains a specific element or not
- How to shuffle a dart list
- Encoding/decoding JSON in Dart explanation with examples
- Dart program to convert a string to double
- How to find the length of a string in Dart
- Dart program to convert hexadecimal to integer