Dung (Donny) Nguyen

Senior Software Engineer

Lists

Working with lists in Dart is pretty straightforward and similar to other programming languages. Lists in Dart are ordered collections of objects. Here’s a quick overview to get us started:

Creating a List

We can create a list in Dart using the List constructor or by using a list literal.

// Using List constructor
List<int> numbers = List<int>.empty(growable: true);

// Using list literal
List<String> fruits = ['Apple', 'Banana', 'Cherry'];

Adding Elements to a List

We can add elements to a list using the add, addAll, and insert methods.

fruits.add('Date');
fruits.addAll(['Elderberry', 'Fig']);
fruits.insert(2, 'Grapes'); // Inserts 'Grapes' at index 2

Accessing Elements

We can access elements in a list using the index.

String firstFruit = fruits[0]; // 'Apple'
String secondFruit = fruits.elementAt(1); // 'Banana'

Updating Elements

We can update elements in a list by assigning a new value to a specific index.

fruits[0] = 'Avocado'; // Update 'Apple' to 'Avocado'

Removing Elements

We can remove elements from a list using the remove, removeAt, and removeWhere methods.

fruits.remove('Banana'); // Removes 'Banana'
fruits.removeAt(1); // Removes the element at index 1
fruits.removeWhere((fruit) => fruit.startsWith('E')); // Removes all elements starting with 'E'

Iterating Over a List

We can iterate over a list using a for loop, forEach, or a for-in loop.

// Using a for loop
for (int i = 0; i < fruits.length; i++) {
  print(fruits[i]);
}

// Using a for-in loop
for (String fruit in fruits) {
  print(fruit);
}

// Using forEach
fruits.forEach((fruit) => print(fruit));

Other Useful Methods

Dart lists come with a variety of other useful methods, such as map, where, reduce, sort, and contains.

List<int> numbers = [1, 2, 3, 4, 5];

// Using map to create a new list with each element squared
List<int> squares = numbers.map((number) => number * number).toList();

// Using where to filter elements
List<int> evenNumbers = numbers.where((number) => number.isEven).toList();

// Using reduce to sum all elements
int sum = numbers.reduce((value, element) => value + element);

// Using sort to sort elements
numbers.sort((a, b) => b.compareTo(a)); // Sort in descending order

// Using contains to check if an element exists
bool hasThree = numbers.contains(3); // true

This should give us a solid foundation to start working with lists in Dart.