Dart List

List is a collection of items.

A list is referenced by a variable name. The items in the list can be accessed using index. Index starts with 0.

Arrays is a common concept in most of the programming languages. In Dart, there is no specific class for Arrays. Dart Lists serve the purpose of Array concept.

In Dart programming language, there are two types of lists based on eligibility of list to change in length.

  1. Fixed Length Lists
  2. Growable Lists

In this tutorial, we will learn about these two types of lists with example Dart programs.

Dart Fixed Length List

In Dart, Fixed Length Lists are the lists which are defined with specific length.

Example

In the following example, we define a Fixed Length List of length 3.

Dart Program

void main(){
	//define list with fixed length
	var myList = new List(3);
	
	//assign list with items
	myList = [25, 63, 84];
	
	print(myList);
}

The statement new List(3); creates a Fixed Length List of length 3.

Output

[25, 63, 84]

Note: For a Fixed Length List, any operations that may change length of the list throw an error.

Dart Growable List

In Dart, Growable Lists are the lists which are defined with items rather than the length unlike Fixed Length Lists.

There are two ways in which you can define a Growable List in Dart. They are:

  1. Assign a List of items directly to a variable.
  2. Create an empty list with no arguments passed to List() in new List().

Example 1

In the following example, we define a Growable List by assigning a list of items directly to a variable.

Dart Program

void main(){
	
	var myList = [25, 63, 84];	
	print(myList);
	
	//add item to growable list
	myList.add(96);
	print(myList);
}

Output

[25, 63, 84]
[25, 63, 84, 96]

Example 2

In the following example, we define an empty Growable List by passing no arguments to List() class and then adding items to the list.

Dart Program

void main(){
	
	var myList = new List();
	
	myList.add(25);
	myList.add(63);
	myList.add(84);
	
	print(myList);
}

Output

[25, 63, 84]

Summary

In this Dart Tutorial, we learned different types of lists and the also seen the different operations that could be performed on lists in Dart programming language.