Dart language has special support for the following collections:
A list is an enumeration of values. The list literal is an enumeration of literal values or expressions separated by comma and enclosed in square brackets. It looks like a List in python or like an Array in JavaScript:
//declare a List object
void main() {
var lst = [1,2,3,];
print(lst); // [1,2,3]
print(lst[0]); // 1 (first element)
print(lst[1]); // 2 (second element)
print(lst[2]); // 3 (last element)
// check length property
assert(list.length == 3);
// check each element
assert(lst[0] == 1); // check
assert(lst[1] == 2); // check
assert(lst[2] == 3); // check
}
This is a special collection that has a wel know theory we learn in school. We know that a "set" is a collection of unique elements. That is, each element is usually a number or a string.
There are several ways to define a set. Most common is to use curly brackets {} and separate elements by comma:
//an empty set of strings
var persons = <Strings>{};
//also an empty set of strings
Set<Strings> names = {};
//a set of strings with 3 elements
var fruits = {'apple', 'orange', 'banana'};
//testing some methods
assert(fruits.length == 3);
fruits.add("lemon")
assert(fruits.length == 4);
A map is a special set that store (key:value) pairs. Therefore in some other languages a map is sometimes called dictionary and sometimes hash table. The secret of maps is that "key" is unique, but unlike a set, the key point to some useful data. This property makes maps more useful than sets.
As for "sets" also we have several ways to define a map.
//an empty map
var gifts = Map();
//new elements
var gifts['doru'] = "pony";
var gifts['marian'] = "bike";
var gifts['dani'] = "bike";
//testing some methods
assert(gifts.length == 3);
//testing some methods
print(gifts['doru']); //expected pony
print(gifts['marian']); //expected bike
print(gifts['dani']); //expected bike
Second way to define a set is by using curly bracket literals {...}.
//an empty map
var gifts = {
'doru' : "pony",
'marian' : "bike"
'dani' : "scutter"
};
Since Map is a generic class, we can use the more explicit notation that should rarely be used. Dart does a good job using type inference so we don't have to use this notation that is actually the only one available in Java for example.
//legacy map declarations
Map<String,String> gifts1 = {};
var gifts2 = <String,String> {};
Note: In Java we need "new" keyword to create an object. In Dart this keyword is optional. So we can call a constructor like a normal function, using name of the class follow by arguments.
Read next: Control Flow