Ways to work with lists in Dart
A very commonly used collection in programming is an array. Dart represents arrays in the form of list objects. A list is simply an ordered group of objects. The dart:core library provides the List class that enables the creation and manipulation of lists.
Lists are iterables
An iterable provides a means to traverse a collection of items in a sequential fashion. Dart takes an approach similar to most other programming languages. Basically, you have what is known as an iterator that keeps track of the current item in a list and allows you to move forward through the list using the next method. More on Darts Iterator can be found on the official website.
In practice, you will find yourself almost always working with some sort of abstraction of the iterator, not the iterator itself. There are multiple classes in the Dart library that you can iterate, but you will work with some more than others. The List is a workhorse and youll find it to be your go-to more often than not. However, its certainly worth knowing about others such as Set, Map, and Queue.
Here is what we will cover in this article:
- Creating lists
- Looping
- Filtering
- Mapping
- Sorting
Creating lists
There are many different ways to create a list. Sometimes youll know the length of your list and sometimes you wont. Both approaches are easily accommodated by Dart. There are even means to dynamically generate a list. Here are some common examples of how to create a list of strings. I chose strings but, as you can imagine, any type would work:
Looping
Looping through a list is very common. For example:
What the above code does is establish a list of strings that contain names. We then create a for loop and print the name out to the console. Here is another way to iterate that list of names:
I like the forEach approach with a fat arrow [=>] function, but the examples essentially do the same thing.
Filtering
Filtering comes into play from the where method:
Essentially, what is happening in the above code is that each price is examined in the fat arrow function and, if it is greater than one dollar, it passes the condition and is added to the overOneDollar result.
Mapping
Mapping allows you to take a list and transform it into something else, ala the map method. For example:
Sorting
The sort method allows you to sort. Default types like numbers and strings dont need much to get started:
Sorting numbers and strings is straight-forward. But what if you had a list of objects to sort? Here is an example that takes a list of Employee objects and ranks them by sales. The employee with the most sales is displayed on top:
This should give you a good start on working with lists, but you should explore the other types of collections Dart has as well.