BASIC DATA STRUCTURE IN FLUTTER/DART
List
is a data structure that represents a collection of elements, where each element has a unique index or position within the list
Declaring a List
1. Using the List constructor:
List numbers = [];
2. Specifying initial values:
List fruits = ['Apple', 'Banana', 'Orange'];
3. Using the List.from constructor:
List temperatures = List.from([25.5, 28.0, 23.8]);
Extracting an element from a list
1. By Index:
int elementAtIndex2 = numbers[2];
print(elementAtIndex2); // Output: 3
2. Using first and last Properties:
int firstElement = numbers.first;
int lastElement = numbers.last;
print(firstElement); // Output: 1
print(lastElement); // Output: 5
Methods
1. add: Adds an element to the end of the list.
List numbers = [1, 2, 3];
numbers.add(4); // Adds 4 to the end of the list.
2. addAll: Adds all elements of an iterable (e.g., another list) to the end of the list.
List numbers = [1, 2, 3];
numbers.addAll([4, 5, 6]); // Adds 4, 5, 6 to the end of the list.
3. remove: Removes the first occurrence of a specified element.
List numbers = [1, 2, 3, 2, 4];
numbers.remove(2); // Removes the first occurrence of 2.
4. removeAt: Removes the element at a specified index.
List numbers = [1, 2, 3, 4];
numbers.removeAt(2); // Removes the element at index 2 (3 in this case).
5. removeLast: Removes and returns the last element of the list.
List numbers = [1, 2, 3];
int lastElement = numbers.removeLast(); // Removes 3 and returns it.
6. indexOf: Returns the first index of a specified element in the list.
List numbers = [1, 2, 3, 2, 4];
int index = numbers.indexOf(2); // Returns the index of the first occurrence of 2 (1 in this case).
7. contains: Checks if the list contains a specified element.
List numbers = [1, 2, 3];
bool containsTwo = numbers.contains(2); // Returns true if 2 is in the list.
8. length: Returns the number of elements in the list.
List numbers = [1, 2, 3, 3];
int length = numbers.length; // Returns 4.
9. isEmpty: Returns true if the list is empty; otherwise, it returns false.
List emptyList = [];
print(emptyList.isEmpty); // Output: true
10. isNotEmpty: Returns true if the list is not empty; otherwise, it returns false
List nonEmptyList = [1, 2, 3];
print(nonEmptyList.isNotEmpty); // Output: true
(note: YouTube doesn't accept angled brackets so I removed them in the List declaration)