In Dart, a List is an ordered collection of elements. It allows you to store multiple values of the same type (or mixed types, if required) in a single variable. Lists in Dart are similar to arrays in other programming languages but offer more flexibility and functionality.
In Dart programming, a List is an ordered collection of objects, similar to arrays in other programming languages. It's a fundamental data structure that allows you to store and manipulate a sequence of elements. Here's a breakdown of Lists in Dart:
Type Declaration:
You can specify the type of elements the list will store (e.g., List<int>, List<String>).
If you do not specify a type, the list will accept any type of element (List<dynamic>).
List Literal:
Lists are commonly created using square brackets [].
List Constructor:
Dart provides constructors like List.filled(), List.empty(), and List.generate() for creating lists with predefined properties.
1. Creating Lists
Using List literals: The most common way to create a list is by using square brackets [] and comma-separated values:
var numbers = [1, 2, 3, 4, 5]; // List of integers
var fruits = ['apple', 'banana', 'orange']; // List of strings
var mixed = [1, 'hello', true, 3.14]; // List of mixed data types
Using the List constructor: You can also create a list using the List constructor. This is useful when you need more control over the list's properties:
var numbers = List<int>.filled(5, 0); // Creates a list of 5 integers, all initialized to 0
var growableList = <String>[]; // Creates an empty growable list of strings
2. Types of Lists
Growable Lists: These are the most common type of lists. They can dynamically change in size, allowing you to add or remove elements as needed. Lists created with literals ([]) or the empty List() constructor are growable by default.
Fixed-length Lists: These lists have a predetermined size that cannot be changed after creation. They are created using the List.filled() constructor. While you can change the values of the elements, you cannot add or remove elements to change the list's length.
3. List Properties and Methods
Dart provides a rich set of properties and methods to work with lists:
length: Returns the number of elements in the list.
add(element): Adds an element to the end of the list (growable lists only).
addAll(iterable): Adds all elements from an iterable to the end of the list (growable lists only).
insert(index, element): Inserts an element at a specific index (growable lists only).
remove(element): Removes the first occurrence of an element (growable lists only).
removeAt(index): Removes the element at a specific index (growable lists only).
indexOf(element): Returns the index of the first occurrence of an element.
contains(element): Checks if the list contains a specific element.
sort(): Sorts the list in ascending order.
forEach(action): Executes a function for each element in the list.
4. Accessing Elements
You can access elements in a list using their index, which starts from 0:
var fruits = ['apple', 'banana', 'orange'];
print(fruits[0]); // Output: apple
print(fruits[1]); // Output: banana
Example Usage:
void main() {
var numbers = [1, 2, 3];
numbers.add(4); // Add an element
numbers.addAll([5, 6]); // Add multiple elements
numbers.insert(0, 0); // Insert at the beginning
print(numbers); // Output: [0, 1, 2, 3, 4, 5, 6]
print(numbers.length); // Output: 7
print(numbers.contains(3)); // Output: true
numbers.forEach((number) {
print(number * 2); // Print each number multiplied by 2
});
}
Lists are a versatile and essential part of Dart programming, used extensively for storing and manipulating collections of data. They offer flexibility with growable and fixed-length options and provide a wide range of methods for efficient data management.
1. Empty List
void main() {
List<int> numbers = [];
print(numbers); // Output: []
}
2. List with Initial Values
void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
print(fruits); // Output: [Apple, Banana, Cherry]
}
3. Dynamic List
If no type is specified, the list can hold elements of mixed types.
void main() {
List<dynamic> mixedList = [1, 'Hello', true];
print(mixedList); // Output: [1, Hello, true]
}
4. Fixed-Length List
Creates a list with a fixed size using List.filled().
void main() {
List<int> numbers = List.filled(5, 0); // Creates a list of size 5, filled with 0.
print(numbers); // Output: [0, 0, 0, 0, 0]
}
5. Growable List
By default, lists are growable when created with []. You can add or remove elements dynamically.
void main() {
List<int> numbers = [];
numbers.add(10);
numbers.add(20);
print(numbers); // Output: [10, 20]
}
6. Using List.generate()
Create a list by generating elements using a function.
void main() {
List<int> squares = List.generate(5, (index) => index * index);
print(squares); // Output: [0, 1, 4, 9, 16]
}
7. Using List.unmodifiable()
Creates a read-only list that cannot be modified.
void main() {
List<int> unmodifiableList = List.unmodifiable([1, 2, 3]);
print(unmodifiableList); // Output: [1, 2, 3]
// unmodifiableList.add(4); // Error: Unsupported operation
}
8. Copying a List
Use the List.from() constructor to create a copy of another list.
void main() {
List<int> original = [1, 2, 3];
List<int> copy = List.from(original);
print(copy); // Output: [1, 2, 3]
}
Type-Safe Lists: Declaring the type ensures type safety. For example:
List<int> numbers = [1, 2, 3]; // Accepts only integers.
// numbers.add('Hello'); // Error: 'Hello' is not an int.
Null Safety: Dart uses null safety, so a list can’t be null unless explicitly marked as nullable.
List<int>? nullableList; // This can hold null.
Spread Operator (...): Allows combining lists.
void main() {
List<int> list1 = [1, 2, 3];
List<int> list2 = [4, 5];
List<int> combined = [...list1, ...list2];
print(combined); // Output: [1, 2, 3, 4, 5]
}
Null-aware Spread Operator (...?): Safely includes null lists.
void main() {
List<int>? nullableList;
List<int> numbers = [1, 2, ...?nullableList];
print(numbers); // Output: [1, 2]
}
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
print(numbers);
}
void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
print('First fruit: ${fruits[0]}');
print('Second fruit: ${fruits[1]}');
}
void main() {
List<String> colors = ['Red', 'Blue'];
colors.add('Green');
print(colors);
}
void main() {
List<int> numbers = [10, 20, 30, 40];
numbers.remove(20);
print(numbers);
}
void main() {
List<String> animals = ['Cat', 'Dog', 'Bird'];
print(animals.contains('Dog')); // true
print(animals.contains('Fish')); // false
}
void main() {
List<String> names = ['Alice', 'Bob', 'Charlie'];
for (String name in names) {
print(name);
}
}
void main() {
List<int> numbers = [5, 3, 8, 1];
numbers.sort();
print(numbers); // [1, 3, 5, 8]
}
void main() {
List<double> prices = [10.5, 20.75, 15.0];
print('Length of list: ${prices.length}');
}
void main() {
List<int> numbers = [1, 2, 3, 4];
List<int> reversedNumbers = numbers.reversed.toList();
print(reversedNumbers); // [4, 3, 2, 1]
}
void main() {
List<int> numbers = [10, 15, 20, 25, 30];
List<int> evenNumbers = numbers.where((n) => n % 2 == 0).toList();
print(evenNumbers); // [10, 20, 30]
}
List Methods/Functions/Operations:
Here are ten Dart programs that demonstrate various operations using the List collection, including sorting, filtering, mapping, reducing, and manipulating elements in different ways.
void main() {
List<String> names = ["Alice", "Bob", "Charlie"];
// Add elements
names.add("Diana");
names.addAll(["Eve", "Frank"]);
// Remove elements
names.remove("Alice");
names.removeAt(0); // Removes "Bob"
// Access elements
print("First name: ${names.first}");
print("Last name: ${names.last}");
print("Names List: $names");
}
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
List<int> evenNumbers = numbers.where((number) => number.isEven).toList();
print("Even Numbers: $evenNumbers");
}
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Multiply each number by 2
List<int> doubled = numbers.map((n) => n * 2).toList();
print("Doubled Numbers: $doubled");
}
void main() {
List<String> fruits = ["banana", "apple", "cherry", "date"];
// Sort alphabetically
fruits.sort();
print("Sorted Fruits: $fruits");
}
void main() {
List<int> numbers = [10, 20, 30, 40, 50];
int sum = numbers.reduce((value, element) => value + element);
print("Sum of numbers: $sum");
}
bool isPrime(int number) {
if (number < 2) return false;
for (int i = 2; i <= number ~/ 2; i++) {
if (number % i == 0) return false;
}
return true;
}
void main() {
List<int> numbers = List.generate(20, (i) => i);
List<int> primes = numbers.where(isPrime).toList();
print("Prime Numbers: $primes");
}
void main() {
List<int> numbers = [5, 3, 8, 1, 2, 10, 7];
int maxNumber = numbers.reduce((a, b) => a > b ? a : b);
int minNumber = numbers.reduce((a, b) => a < b ? a : b);
print("Max: $maxNumber, Min: $minNumber");
}
void main() {
List<String> words = ["apple", "banana", "cherry", "date", "fig", "grape"];
Map<int, List<String>> groupedByLength = {};
for (var word in words) {
groupedByLength.putIfAbsent(word.length, () => []).add(word);
}
print("Words grouped by length: $groupedByLength");
}
void main() {
List<int> numbers = [1, 2, 2, 3, 4, 4, 5, 6, 7, 7];
List<int> uniqueNumbers = numbers.toSet().toList();
print("Unique Numbers: $uniqueNumbers");
}
void main() {
List<Map<String, dynamic>> students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 95},
{"name": "Charlie", "score": 80},
];
// Sort students by score
students.sort((a, b) => b["score"].compareTo(a["score"]));
students.forEach((student) {
print("${student['name']} scored ${student['score']}");
});
}
These programs illustrate various uses of the List collection in Dart, from basic manipulations to advanced filtering, mapping, and sorting, showcasing the versatility of lists in handling and organizing data.