Recently I’ve been blogging about Flutter and I thought it would be good to take some time off that subject and explore the programming language used by Flutter – Dart. So here we are! This is the first post in what is to be a journey through the fundamentals of Dart. I’m going to kick off this series with an exploration of working with lists. The documentation put together from the dart team is extremely well done but examples are always handy right?
Lists are Iterables
An iterable provides a means to traverse items some sort of a list in a sequential fashion. Dart takes an approach similar to most other programming languages. Basically you have what is known as an iterator which keeps track of the current item in a list and allows you to move forward through the list using a ‘next’ method. More on Dart’s Iterator can be found here however in practice you will find you are 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 and some you will work with more than others. List is a workhorse and you’ll find it being your go-to more often than not. But it’s certainly worth knowing about others such as Set, Map, and Queue.
Here is what we will cover in this tutorial:
There are many different ways to create a list. At times you’ll know the length of your list, and at times you won’t. Both approaches are easily accommodated by dart. There are even means to dynamically generate a list. Here are some common examples of creating a list of strings. I chose strings but as you can imagine, any type here would work:
Looping through a list is very common. For example:
What the above code does is establish a list of strings that contain names. Then we create a for loop and print the name out to the console. Here is another way to iterate that list of names:
I personally prefer the forEach approach with a fat arrow (=>) function but the examples essentially do the same thing.
Filtering comes into play from the where method:
Essentially what is happening in the above code is 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 allows you to take a List and transform it into something else a’la the map method. For example:
The sort method allows you to sort. Default types like numbers and strings don’t 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 Employees and ranks their Sales with the Employee with the most Sales being displayed on top and so forth:
This should give you a good start on working with lists. But you should explore the other types of collections Dart has as well. In the meantime, if you have any other examples you wish to share, feel free to comment below!