One of the first features that you generally meet when you learn a new language are arrays. In Dart, you use List objects when you want to define a collection.
Consider the following code:
void main() {
String mySongs = sing();
print (mySongs);
}
String sing() {
var songs = List<String>();
var songString = '';
songs.add('We will Rock You');
songs.add('One');
songs.add('Sultans of Swing');
int i=0;
while (i < songs.length) {
songString += '${songs[i]} - ';
i++;
}
return songString;
}
In the main() method, we are calling the sing() method and printing its result. The sing() method defines a list of strings:
var songs = List<String>();
A list can contain several types of objects. You could have a list of integers, Booleans, or even user-defined objects. You can also avoid specifying the kind of object that is contained in a list by just writing the following:
var songs = List();
The <String> after List is the generic syntax. The use of generics enforces a restriction on the type of values that can be contained in the collection, creating a type-safe collection.
Lists implement several methods. You use the add() method to insert a new object into the collection:
songs.add('We will Rock You');
The new object is added to the end of the list. You could reach exactly the same result by writing the following code:
var songs = ['We will Rock You', 'One', 'Sultans of Swing'];
The songs variable would still be a list of strings. If you tried to add a different data type, such as songs.add(24), you would get an error. This is because an integer cannot be inserted into a list of strings, and type safety is enforced by default.
The while statement contains the condition that needs to be true for the loop to continue:
while (i < songs.length) {
When the condition (i < songs.length) becomes false, the code in the loop won't execute anymore.
As you've already seen before, the += operator is a concatenation of strings. The $ character allows you to insert expressions into quotes:
songString += '${songs[i]} - ';
Here is the end result of the full code:
As you can see, the three wonderful songs are concatenated, and after each song, you've added a - sign.
Now, let's see a few interesting features that you can leverage while using lists in Dart.