Often times, you’ll want to combine lists and with Dart, this is actually quite easy to do. We use the plus operator between two lists, and basically, we add the two lists together. So Dart makes this operation really easy to do.
Lets say you have picked three cards and I picked three cards and we want to combine them into a singular deck along with an existing card, we might do something like this:
You’ve actually just created a list, but not one that you intended to make.
Your list now contains two other lists and a string. Instead of passing in each card, you effectively passed in the stack of cards for your cards and my cards. This mean, your first and second element in the list is another list. The last element is 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 a list for you. This operator looks like three regular dots and it comes in two flavors - a regular version and a null aware version. Let’s see it action.
To get started, open up a new Dartpad. We’ll create our two lists of cards.
var yourCards = ['8♦️', '3♣️', 'J♠️'];
var myCards = ['10❤️', 'Q♦️', '2♠️'];
Now let’s add our bonus card. We will make it an ace of spades.
var bonusCard = 'A♠️';
Now lets combine all the cards together. First, let’s create a simple list as I just demonstrated.
var cards = [yourCards, myCards, bonusCard];
And let’s print it out.
print(cards);
Give it a run. You’ll notice all of our cards now contained in a single list, but it also contains two lists as indicated by the brackets. We want to spread it out so lets add the spread operator before each of our lists.
var cards = [...yourCards, ...myCards, bonusCard];
Now when we re-run our program, you’ll see that all our cards are now listed as individual elements. Okay, but what happens if we get a null list. Add the following:
List<String>? emptyHand = null;
In this case, we create a null list. Previously, when 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 some problems. Add the null list to the cards.
var cards = [...yourCards, ...myCards, bonusCard, ...emptyHand];
You’ll see we get an error. If we run the program, we get a compile error warning 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. Just put a question mark after the dots.
var cards = [...yourCards, ...myCards, bonusCard, ...emptyHand];
And now the compile error goes away. Run the program. This time, it runs just like before. Nice work.