The List is to create an integer indexed collection of objects, that each objects are identified or accessed by index.
An List
or Array
is a data structure consisting of a collection of elements like values or variables.
Array is a collection of objects. In Dart, arrays are List objects.
A list may contain zero or more objects.
A non-empty list has first element at 0
index and last element at list.length-1
index
You can create and initialize lists in multiple ways:
The List class also defines several methods for manipulating list values or variables, like, add, remove and sort etc.
The list literal is to create a single object of a list.
The following code snippet shows how to create list using list literal.
// List of integers
var numberList = [1, 2, 3, 4, 5]; // List<int>
// list of strings
var stringList = ['Item1', 'Item2']; // List<String>
The list constructor is to create object of a List that can be initiated into multiple instances with new
keyword.
The following code snippet shows how to create a list using its constructor.
// list of integers
var numberList = List();
// Add values to a list.
numberList.add(1);
numberList.add(2);
// list of strings
var stringList = List();
// Add values to a list.
stringList.add('Item1');
stringList.add('Item2');
var list = ['Item1', 'Item2'];
'Item1', 'Item2'
are evaluated in order they appear in the program producing objects.list
, of size 2 allocated.list
.list
object.The fixed-length list is to create list with fixed length, we cannot add new values to this list.
We can create fixed-length list by specifying the length.
The following code snippet shows how to create a fixed length list.
main() {
var products = List(2);
// only we can add two elements to the list by indexer
products[0] = 'Product 1';
products[1] = 'Product 2';
print(products); // [Product 1, Product 2]
}
main() {
var products = List(2);
products.add('Product 1'); // Error
}
main() {
var products = List(2);
products.length = 3; // Error
}
The growable list is to grow the capacity of list when necessary.
We can create growable list by not specify the length of the List.
The following code snippet shows how to create a growable list.
main() {
var products = List();
products.add('Product 1');
products.add('Product 2');
products.add('Product 3');
// print all products to console
print(products); // [Product 1, Product 2, Product 3]
}
The list has length 0 and is growable because the length
is omitted.
The parameterized type list literal is to create a single object of a list by explicitly defining the type to the List, which only allows the values of same type objects.
Use syntax like <data type>
to declare:
The following code snippet shows how to create list of integers and list of strings with type using list literal.
//list of integers only
var numberList = <int>[1, 2, 3, 4, 5];
// list of strings only
var stringList = <String>['Item1', 'Item2', 'Item3'];
The parameterized type list constructor is to create object of a List by explicitly defining the type to the List, which only allows the values of same type objects.
Use syntax like List<type>
to declare:
The following code snippet shows how to create list of integers and list of strings with the type using list constructor.
// list of integers
var numberList = List<int>();
numberList.add(1);
numberList.add(2);
// list of strings
var stringList = List<String>();
stringList.add('Item1');
stringList.add('Item2');
The constant list is to create unmodifiable list, that cannot be modified after they are created.
A constant list literal evaluated at compile time.
Attempting to modify a constant list literal will result in a dynamic error.
use const
keyword to define constant list
The following code snippet shows how to create a constant list.
main() {
//add const before the list literal
var list = const [1, 2, 3, 4, 5];
list[1] = 1; // Error Cannot modify an unmodifiable list
}
The spread operator(...) is to insert a list object in to another list.
Use ...
operator.
The following code snippet shows how to insert the list of object in to another list.
main() {
var outOfStock = ['Product 1', 'Product 2'];
// use spread operator to insert list
var allProducts = [...outOfStock, 'Product 3', 'Product 4'];
// print all products to console
print(allProducts); // [Product 1, Product 2, Product 3, Product 4]
}
The Null-aware spread operator(...?
) is to avoid runtime exception while inserting a null
list object in to another list.
Use ...?
operator
The following code snippet shows how to avoid runtime exception while inserting a null
list object.
main() {
var list = null;
var list2 = [...list, 6, 7]; // Error The getter 'iterator' was called on null.
// handle nullable list using ...?
var list3 = [...?list, 6, 7]; // OK
}
The collection if is to build List using if
condition, i.e. manipulate the item of a List before adding them.
The following code snippet shows how to build list using if
condition.
bool isThirdItemAvailable = true;
var list = [
'Item1',
'Item2',
if (isThirdItemAvailable) 'Item3',
];
print(list); // {Item1, Item2, Item3}
The collection for
is to build List using repetition for
condition, i.e. manipulate the items of a list before adding them:
The following code snippet shows how to build list using repetition for
condition.
var list = [
'Item2',
'Item3',
'Item4',
];
var otherList = ['Item1', for (var item in list) item];
print(otherList); // [Item1, Item2, Item3, Item4]
The add()
method is to add value
to the end of this list.
Its extends the length of list by one.
The following code snippet shows how to add a new value to this list.
main() {
var list = ['Item1', 'Item2'];
// add new value to list
list.add('Item3');
// print elements of this list to console.
print(list); // [Item1, Item2, Item3]
}
The addAll()
method is to append the list of objects to the end of this list.
It extends the length of the list by the number of objects in iterable
.
The following code snippet shows how to add the list of object to this list.
main() {
var list = ['Item1', 'Item2'];
// Append the list of object to this list
list.addAll(['Item3', 'Item4']);
// print objects of this list
print(list); // [Item1, Item2, Item3, Item4]
}
The remove()
method is to remove the first occurrence of value
from this list.
Returns true
if value
was in the list, otherwise return false
.
The following code snippet shows how to remove the element from the list by value.
main() {
var list = ['Item1', 'Item2', 'Item3'];
// return true or false
var isRemoved = list.remove('Item2');
// print true because the given value was in the list
print(isRemoved); // true
// print remaining elements of list after removing the value from the list.
print(list); // [Item1, Item3]
}
Note: The method has no effect if value
was not in the list.
// return true or false
var isRemoved = list.remove('Item4');
// print false, because the given value was not in the list.
print(isRemoved); // false
The removeAt()
method is to remove the object at position index
from this list.
It returns the removed object. This method reduces the length of list by one and moves all later objects down by one position.
The following code snippet shows how to remove the element from the list by index
.
main() {
var list = ['Item1', 'Item2', 'Item3'];
// remove the element from the list by index
var removedObject = list.removeAt(1);
// print to console remove object
print(removedObject); // Item2
// print to console remaining elements of the list after removed by index.
print(list); // [Item1, Item3]
}
The clear()
method is to remove all objects from this list; the length of the list becomes zero.
The following code snippet shows how to remove all the elements of the list.
main() {
var list = ['Item1', 'Item2', 'Item3'];
list.clear();
print(list); // []
}
The sort method is to sort the list according to the order specified by the compare
function.
The compareTo()
method is to compares this string to other.
The following code shows how to sort the element of the list in alphabetical order.
main() {
var skills = ['Javascript', 'Angular', 'React', 'Flutter'];
// Sort a list.
skills.sort((a, b) => a.compareTo(b));
print(skills); // [Angular, Flutter, Javascript, React]
}
The forEach()
method is to apply a function to each element of the list in iteration order.
The following code snippet shows how to apply print function to each element of the list to print to console.
main() {
var skills = ['Javascript', 'Angular', 'React'];
skills.forEach((skill) => print('$skill Tutorial'));
// Javascript Tutorial
// Angular Tutorial
// React Tutorial
}
The map()
method is to return a new lazy Iterable with elements that are created by calling function
on each element of the list.
The following code snippet shows how to return a new Iterable by making all the elements to upper case.
main() {
var skills = ['Javascript', 'Angular', 'React'];
var result = skills.map((skill) => skill.toUpperCase());
result.forEach(print);
// JAVASCRIPT ANGULAR REACT
}
The where()
method is to filter the list and return the matching elements. It returns a new lazy iterable.
The matching elements have the same order in the returned iterable as they have in [iterator]
main() {
var skills = ['Javascript', 'Angular', 'React'];
var result = skills.where((skill) => skill == 'React');
result.runtimeType; // Iterable<String>
result.forEach(print); // React
}
The any()
method is to check whether any item of this list satisfies condition([test]).
It checks every element in iteration order, and returns true
if any of them satisfies the condition([test]), otherwise returns false
.
main() {
var skills = ['Javascript', 'Angular', 'React'];
if (skills.any((skill) => skill.contains('React'))) {
print('The list satisfies give test');
}
print(skills.any((skill) => skill.contains('React'))); // true
}
The every()
method is to check whether every element of this list satisfies condition(test
).
It checks every element in iteration order, and returns false
if any of them not satisfies the condition([test]), otherwise returns true
.
main() {
var skills = ['Javascript', 'Angular', 'React'];
if (skills.every((skill) => skill.contains('a'))) {
print('The list satisfies give test');
}
print(skills.every((skill) => skill.contains('a'))); // true
}
The length
property is to get the number of objects in this list
main() {
var list = [
'Product 0',
'Product 1',
'Product 2',
'Product 3',
];
list.length;
print(list.length); // 4
}
The valid indices for a list are 0
through length - 1
. 0
is the first element of the list and length - 1
is the last element of the list.
The isEmpty
property is to check for empty list, returns true if there is no values in the list.
main() {
var list = [];
if (list.isEmpty) {
print('The list is empty');
}
}
The isNotEmpty
property is to check for non empty list, returns true if there is at least one value in the list.
main() {
var list = [
'Product 0',
'Product 1',
'Product 2',
'Product 3',
];
if (list.isNotEmpty) {
print('The list is not empty');
}
}
The indexOf()
method is to returns the first index of given element in this list.
The following code snippet shows how to get the index of the element Product 1
from the list.
main() {
var list = [
'Product 0',
'Product 1',
'Product 2',
'Product 3',
];
var index = list.indexOf('Product 1');
print(index); // 1
}
You can also define from where the searching of element should start, by providing optional position parameter start
with value.
The following code snippet shows how to get index of element Product 2
, by start searching from the index 1
.
// searching start from index 2 i.e from second element of the list
var index = list.indexOf('Product 2', 1); // 2
If the given element is not found in the list, its returns -1 value.
var index = list.indexOf('Product 5'); // -1