Intro To Lists In Dart – Dart Programming Lists Guide

Haris Bin Nasir Avatar

·

·

In Dart, a List is an ordered collection of items, often referred to as an array in other programming languages. Lists allow you to store multiple elements of the same type and access them using an index. Dart lists are versatile and provide a wide range of methods for adding, removing, and manipulating elements.

For further information on detailed topics of Dart, click here.

1. Creating a List

You can create a list in Dart using the List constructor or by using list literals.

Example 1: Creating a List with Literal Notation
void main() {
  List<String> fruits = ['Apple', 'Banana', 'Cherry'];
  print(fruits);  // Output: [Apple, Banana, Cherry]
}

In this example, the fruits list stores a collection of strings, representing different fruit names.

Example 2: Creating a List Using the List Constructor
void main() {
  List<int> numbers = List.filled(3, 0);  // Create a list of 3 elements, all initialized to 0
  print(numbers);  // Output: [0, 0, 0]
}

Here, the numbers list is created using the List.filled constructor, which initializes a list with a specified length and fills it with a default value.

2. Accessing List Elements

You can access elements in a list using their index, which starts at 0.

Example 1: Accessing Elements by Index
void main() {
  List<String> fruits = ['Apple', 'Banana', 'Cherry'];
  print(fruits[0]);  // Output: Apple
  print(fruits[2]);  // Output: Cherry
}

In this example, you access the list elements using their respective indices.

Example 2: Using first and last Properties
void main() {
  List<int> numbers = [10, 20, 30, 40];
  print(numbers.first);  // Output: 10
  print(numbers.last);  // Output: 40
}

The first and last properties provide a convenient way to access the first and last elements of a list.

3. Modifying List Elements

You can modify elements in a list by accessing them through their index or by using methods like add, insert, and remove.

Example 1: Updating an Element by Index
void main() {
  List<String> fruits = ['Apple', 'Banana', 'Cherry'];
  fruits[1] = 'Blueberry';  // Update the element at index 1
  print(fruits);  // Output: [Apple, Blueberry, Cherry]
}

In this example, the element at index 1 (originally 'Banana') is updated to 'Blueberry'.

Example 2: Adding and Removing Elements

void main() {
  List<int> numbers = [1, 2, 3];
  numbers.add(4);  // Add an element to the end of the list
  print(numbers);  // Output: [1, 2, 3, 4]
  
  numbers.remove(2);  // Remove the element with value 2
  print(numbers);  // Output: [1, 3, 4]
}

In this example, elements are added and removed from the list using the add and remove methods.

4. Iterating Over a List

You can iterate over the elements in a list using loops, such as for, for-in, and forEach.

Example 1: Iterating with a For Loop
void main() {
  List<String> fruits = ['Apple', 'Banana', 'Cherry'];
  for (int i = 0; i < fruits.length; i++) {
    print(fruits[i]);
  }
}
// Output:
// Apple
// Banana
// Cherry

In this example, a for loop is used to iterate through the list and print each element.

Example 2: Iterating with For-Each
evoid main() {
  List<int> numbers = [10, 20, 30, 40];
  numbers.forEach((number) {
    print(number);
  });
}
// Output:
// 10
// 20
// 30
// 40

Here, the forEach method is used to iterate through the list and print each element.

5. List Methods and Properties

Dart provides a variety of methods and properties to work with lists, such as length, isEmpty, isNotEmpty, addAll, and clear.

Example 1: Using List Properties
void main() {
  List<String> fruits = ['Apple', 'Banana'];
  print(fruits.length);  // Output: 2
  print(fruits.isEmpty);  // Output: false
  print(fruits.isNotEmpty);  // Output: true
}

In this example, the length, isEmpty, and isNotEmpty properties are used to retrieve information about the list.

Example 2: Using List Methods
void main() {
  List<int> numbers = [1, 2, 3];
  numbers.addAll([4, 5, 6]);  // Add multiple elements to the list
  print(numbers);  // Output: [1, 2, 3, 4, 5, 6]
  
  numbers.clear();  // Clear all elements from the list
  print(numbers);  // Output: []
}

In this example, the addAll method is used to add multiple elements to the list, and the clear method removes all elements.

6. List of Lists

Dart also supports lists containing other lists, allowing you to create multi-dimensional collections.

Example 1: Creating a List of Lists
void main() {
  List<List<int>> matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ];
  
  print(matrix[1][2]);  // Output: 6
}

In this example, you create a 2D list (or matrix) and access an element using two indices.

Example 2: Iterating Over a List of Lists
void main() {
  List<List<int>> matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
  ];
  
  for (List<int> row in matrix) {
    for (int value in row) {
      print(value);
    }
  }
}
// Output:
// 1
// 2
// 3
// 4
// 5
// 6

In this example, you use nested loops to iterate over the elements in a 2D list.

7. Working with Null Values in Lists

Dart lists can contain null values, but handling null elements carefully is essential to avoid errors.

Example 1: Checking for Null Elements
void main() {
  List<String?> names = ['Alice', null, 'Charlie'];
  
  for (String? name in names) {
    if (name != null) {
      print('Hello, $name!');
    } else {
      print('No name provided.');
    }
  }
}
// Output:
// Hello, Alice!
// No name provided.
// Hello, Charlie!

In this example, the null value in the list is checked before using it, preventing potential errors.

Example 2: Filtering Out Null Values
void main() {
  List<String?> names = ['Alice', null, 'Charlie'];
  List<String> nonNullNames = names.whereType<String>().toList();
  
  print(nonNullNames);  // Output: [Alice, Charlie]
}

Here, the whereType method is used to filter out null values and create a new list with only non-null elements.

Conclusion

Dart lists are powerful and flexible collections that allow you to store, manipulate, and iterate over ordered elements efficiently. Whether you’re creating simple lists, modifying elements, or working with multi-dimensional data, understanding how to use lists in Dart will greatly enhance your ability to manage data in your applications. By mastering the various methods and properties provided by the List class, you can write more efficient and effective Dart code.

Happy Coding…!!!

Leave a Reply

Your email address will not be published. Required fields are marked *