LISTS IN DART(Flutter)

LISTS IN DART(Flutter)

Dart List is similar to an array, which is the ordered collection of the objects. The array is the most popular and commonly used collection in any other programming language. The Dart list looks like the JavaScript array literals. The syntax of declaring the list is given below.

var list1 = [10, 15, 20,25,25]

The Dart list is defined by storing all elements inside the square bracket ([]) and separated by commas (,).

Types of Lists

The Dart list can be categorized into two types -

  • Fixed Length List

  • Growable List

Fixed Length List

The fixed-length lists are defined with the specified length. We cannot change the size at runtime. The syntax is given below.

Syntax - Create the list of fixed-size

var list_name = new List(size)

The above syntax is used to create the list of the fixed size. We cannot add or delete an element at runtime. It will throw an exception if any try to modify its size.

The syntax of initializing the fixed-size list element is given below.

Syntax - Initialize the fixed size list element

list_name[index] = value;

Example -

void main() {

var list1 = new List(5);

list1[0] = 10;

list1[1] = 11;

list1[2] = 12;

list1[3] = 13;

list1[4] = 14;

print(list1);

}

Output:

[10, 11, 12, 13, 14]

Explaination -

In the above example, we have created a variable list1 that refers the list of fixed size. The size of the list is five and we inserted the elements corresponding to its index position where 0th index holds 10, 1st index holds 12, and so on.

Growable List

The list is declared without specifying size is known as a Growable list. The size of the Growable list can be modified at the runtime. The syntax of the declaring Growable list is given below.

Syntax - Declaring a List

// creates a list with values

var list_name = [val1, val2, val3]

Or

// creates a list of the size zero

var list_name = new List()

Syntax - Initializing a List

list_name[index] = value;

Consider the following example -

Example - 1

void main() {

var list1 = [10,11,12,13,14,15];

print(list1);

}

Output:

[10, 11, 12, 13, 14, 15]

In the following example, we are creating a list using the empty list or List() constructor. The add() method is used to add element dynamically in the given list.

THANK YOU!