Lists in Dart

Lists in Dart#

About#

A List in Dart is an ordered collection of items, where each item is identified by its index. The index starts at 0. Lists allow duplicate elements and are widely used when the order of elements matters.

How Lists Work#

  • Lists store multiple values of the same or different types.
  • Elements in a list can be accessed by their index.
  • Dart provides two types of lists: Fixed-length (length cannot change) and Growable (length can change by adding or removing elements).

List Types:#

  1. Fixed-length List: Defined with a specific length and cannot grow or shrink.
  2. Growable List: Dynamically grows or shrinks as items are added or removed.

Usage#

Lists are useful when you need:

  • An ordered collection of items.
  • Easy access to elements using an index.
  • To store multiple values, possibly of the same type.

Common Operations:#

  • Access elements: list[index]
  • Modify elements: list[index] = value
  • Add elements: list.add(value)
  • Remove elements: list.remove(value)
  • Length of list: list.length

Example#

Example 1: Growable List#

void main() {
  // Creating a growable list
  List<int> numbers = [1, 2, 3];
  
  // Accessing elements by index
  print(numbers[0]); // Output: 1
  
  // Modifying an element
  numbers[1] = 10;
  
  // Adding an element
  numbers.add(4);
  
  // Removing an element
  numbers.remove(10);
  
  // Printing the list
  print(numbers); // Output: [1, 3, 4]
}

Conclusion#

A List in Dart is a versatile collection that allows you to store ordered data. It supports various operations, such as accessing, modifying, adding, and removing elements, making it highly useful for scenarios where ordered data and duplicates are required.