Dart Lists

In Dart, 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.

There are two types of lists based on mutability (ability 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. Once defined, we cannot change the length of these Lists.

Example

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

main.dart

</>
Copy
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 we 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.

main.dart

</>
Copy
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, and then add items to the list.

main.dart

</>
Copy
void main() {
  var myList = [];

  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.