Is there an efficient way to iterate through objects in the list in reverse order in dart? I could use indices, but will that cause a performance hit (i.e. if List<E>
is built internally using linked list)?
Context: I'm drawing objects from back to front, but need to process them from front to back
Ali
We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method.
C++ Iterators Reverse Iterators A reverse iterator is made from a bidirectional, or random access iterator which it keeps as a member which can be accessed through base() . To iterate backwards use rbegin() and rend() as the iterators for the end of the collection, and the start of the collection respectively.
2. Using Apache Common Collections. Apache Common provides ReverseListIterator that we can use to iterate list in reverse order. The first call to next() will return the last element from the list, the next call to next() will return the previous element, and so on.
You can now reverse the iteration of a list in Dart. Use the reversed
getter on List.
var fruits = ['apples', 'oranges', 'pears']; Iterable inReverse = fruits.reversed; var fruitsInReverse = inReverse.toList(); print(fruitsInReverse); // [pears, oranges, apples]
You could shorten this to:
var fruits = ['apples', 'oranges', 'pears']; print(fruits.reversed.toList());
See the API docs.
Until the issue #2804 has been fixed, you have to iterate list in reverse order using indices. For your performance concern, it should be good because Lasse R.H. Nielsen once said :
Lists in Dart are intended for random access
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With