Arrays are one of the most commonly used collections in programming. In Dart, an array is represented in the form of a list (i.e., an ordered collection of objects).
Lists in Dart are further classified into fixed-length lists and growable lists.
As the name suggests, the length of a fixed-length list is fixed and cannot be changed at runtime. The syntax for declaring a fixed-length list is:
var list_name = new List(size)
The code snippet below demonstrates how a fixed-length list can be used:
import 'dart:convert'; void main() { var size = 5; var myList = new List(5); myList[0] = 'Quentin'; myList[1] = 'Scorsese'; myList[2] = 'Nolan'; myList[3] = 'Anderson'; myList[4] = 'Kubrick'; print(myList); }
The length of a growable list can be changed at runtime.
The syntax for declaring a growable list with some predefined values is:
var list_name = [val1, val2, val3]
The syntax for declaring a growable list with an initial size of zero is:
var list_name = new List()
The code snippet below demonstrates the usage of a growable list, where add
and remove
are used for insertion and deletion, respectively:
import 'dart:convert'; void main() { var myList = [10, 20, 30]; print("Original list: $myList"); print("Adding elements to the end of the list..."); myList.add(40); myList.add(50); print(myList); print("Removing '10' from the list..."); myList.remove(10); print(myList); }
RELATED TAGS
View all Courses