Previous episode: 14. Create a Conditional List
Next episode: 16. Conclusion
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
Oftentimes you'll want to combine lists with Dart, and this is actually quite easy to do. We have the plus operator between two lists, and basically we add the two lists together. So Dart makes this operation really easy. Now, let's say you pick three cards and I pick three cards, and we want to combine them into a singular deck, along with an existing card. You might write code something like this. You've actually just created a list, but not one you intended to make, your list now contains two other lists and a string, instead of passing in each card, you've effectively passed in the stack of cards for your cards and my cards. This means your first and second element in the list, is another list. The last element is a string. Rather, you want to spread out the cards in the list as individual elements, and for that you use the spread operator. The spread operator takes all the elements out of the list for you. The operator looks like three regular dots, and comes in two flavors, a regular version and a null aware version. Let's see it in action. To get started, open up a new Dart pad. We'll create our two lists of cards. Now let's add our bonus card, we'll put this in a list. Let's combine all the cards together. First, let's create a simple list as I just demonstrated. Now let's print it out. Give it a run. You'll notice that all our cards are now contained in a single list, but it also contains three lists as indicated by the brackets. We want to spread it out, so let's add the spread operator before each of our lists. Now, when we rerun our program, you'll see that all our cards are listed as individual elements. Okay, what happens if we get a null list? Add the following. In this case, we create a null list. Previously, we played with lists and null values, that is the elements in the list could be null. In this case, the entire list can be null. As you can imagine, this will cause you some problems. Add the null list to the cards. If we run the program, we get an error, warning us that a null value must be null checked. There's actually a null spread operator, this operator will see if the target list is null, and if it is, it will disregard it. Just put a question mark after the dots. And now the error goes away. Run the program. This time it runs just like before, nice work.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.