Tags

, , , , , , , , , , , , , , ,

laern-dart-the-hard-way

Learn Dart the Hard Way

This is the most common collection in every programming language: array or an “ordered group of objects”. In Dart, arrays are List objects. We will address them as ‘lists’ in our future discussion.
JavaScript array literals look like Dart lists. Here is a sample code we may consider to understand why this concept is important:

//code 2.14
main(List arguments) {
List fruitCollection = ['Mango', 'Apple', 'Jack fruit'];
print(fruitCollection[0]);
}

Consider another piece of code:

//code 2.15
main(List arguments) {
List fruitCollection = ['Mango', 'Apple', 'Jack fruit'];
var myIntegers = [1, 2, 3];
print(myIntegers[2]);
print(fruitCollection[0]);
}

What is the difference between these two code snippets? In the above code 2.14, we have explicitly mentioned that we are going to declare a collection of fruits. And we can pick any item from that collection from the key.

As we know, when in an array key is not mentioned with the value pair, it automatically infers that the key starts from 0. Therefore, the output of code 2.14 is ‘Mango’. In the second instance,

we do not have any explicit declaration about the ‘myInteger’ lists. We have written: var myIntegers = [1, 2, 3]; however, Dart infers that list has type List. Let us see the output of the code 2.15:

//output of code 2.15
3
Mango

If we try to inject non-integer objects to the ‘myInteger’ list, what happens?

//code 2.17
main(List arguments) {
List fruitCollection = ['Mango', 'Apple', 'Jack fruit'];
var myIntegers = [1, 2, 3, 'non-integer object'];
print(myIntegers[3]);
print(fruitCollection[0]);
}

It did not raise any error. See the output:

//output of code 2.17
non-integer object
Mango

Only remember, Dart Lists use zero-based indexing like all other collections we have seen in other programming languages. Just think it as a key=>value pair, where 0 is the index of the first value or element. As we progress, we will discuss Lists as there are other useful methods around that we will use when we will build our first mobile application. Dart Lists have many handy methods.