Lists are one of the most commonly used data structures in Dart. A List is an ordered collection of items that can grow or shrink dynamically. Understanding how to work with lists effectively is crucial for managing collections of data in your applications.
Creating Lists
Dart provides multiple ways to create lists. You can create fixed-length lists or growable lists, and specify the type of elements they contain.
List Creation Methods
1// Creating a list with initial values2List<String> fruits = ['Apple', 'Banana', 'Orange'];3print(fruits); // [Apple, Banana, Orange]4 5// Type inference with var6var numbers = [1, 2, 3, 4, 5]; // Dart infers List<int>7 8// Empty growable list9List<int> scores = [];10List<String> names = <String>[]; // Alternative syntax11 12// Creating a list with a specific length (fixed-size)13List<int> fixedList = List.filled(5, 0); // [0, 0, 0, 0, 0]14 15// Creating a growable list with initial capacity16List<String> cities = List.empty(growable: true);17 18// List from another iterable19List<int> copy = List.from([1, 2, 3]);20List<int> generated = List.generate(5, (index) => index * 2);21print(generated); // [0, 2, 4, 6, 8]22 23// Spread operator to combine lists24var list1 = [1, 2, 3];25var list2 = [4, 5, 6];26var combined = [...list1, ...list2]; // [1, 2, 3, 4, 5, 6]HintLists can be created in various ways depending on your needs. Use literal syntax [] for most cases, and List.generate() for creating lists based on a pattern.
Accessing List Elements
You can access list elements using index notation. Dart lists are zero-indexed, meaning the first element is at index 0.
Accessing and Modifying Elements
1List<String> colors = ['Red', 'Green', 'Blue', 'Yellow'];2 3// Accessing elements by index4print(colors[0]); // Red (first element)5print(colors[2]); // Blue (third element)6 7// Accessing first and last elements8print(colors.first); // Red9print(colors.last); // Yellow10 11// Getting list length12print(colors.length); // 413 14// Checking if list is empty15print(colors.isEmpty); // false16print(colors.isNotEmpty); // true17 18// Modifying elements19colors[1] = 'Purple';20print(colors); // [Red, Purple, Blue, Yellow]21 22// Safe access with elementAt23print(colors.elementAt(0)); // Red24 25// Getting a range of elements26print(colors.sublist(1, 3)); // [Purple, Blue]27 28// Checking if element exists29print(colors.contains('Red')); // true30print(colors.contains('Orange')); // false31 32// Finding index of element33print(colors.indexOf('Blue')); // 234print(colors.indexOf('Orange')); // -1 (not found)HintAlways ensure the index is within bounds (0 to length-1) to avoid RangeError. Use contains() to check if an element exists before accessing it.
Adding and Removing Elements
Dart provides various methods to add and remove elements from lists. These operations modify the list in place.
List Modification Methods
1List<String> tasks = ['Study', 'Exercise'];2 3// Adding elements4tasks.add('Cook'); // Add at end5print(tasks); // [Study, Exercise, Cook]6 7tasks.addAll(['Clean', 'Read']); // Add multiple8print(tasks); // [Study, Exercise, Cook, Clean, Read]9 10tasks.insert(1, 'Work'); // Insert at index11print(tasks); // [Study, Work, Exercise, Cook, Clean, Read]12 13tasks.insertAll(0, ['Wake up', 'Breakfast']);14print(tasks); // [Wake up, Breakfast, Study, Work, Exercise, Cook, Clean, Read]15 16// Removing elements17tasks.remove('Work'); // Remove by value18print(tasks); // [Wake up, Breakfast, Study, Exercise, Cook, Clean, Read]19 20String removed = tasks.removeAt(0); // Remove by index21print('Removed: $removed'); // Removed: Wake up22print(tasks); // [Breakfast, Study, Exercise, Cook, Clean, Read]23 24String last = tasks.removeLast(); // Remove last element25print('Removed last: $last'); // Removed last: Read26 27// Remove multiple elements28tasks.removeRange(1, 3); // Remove from index 1 to 3 (exclusive)29print(tasks); // [Breakfast, Cook, Clean]30 31// Remove elements that match a condition32tasks.removeWhere((task) => task.length > 5);33print(tasks); // [Cook, Clean]34 35// Clear all elements36tasks.clear();37print(tasks); // []HintUse add() and remove() for single elements, addAll() and removeWhere() for multiple elements. Remember that removing elements shifts the indices of subsequent elements.
Iterating Over Lists
There are multiple ways to iterate through list elements in Dart, each suitable for different scenarios.
List Iteration Techniques
1List<int> numbers = [10, 20, 30, 40, 50];2 3// 1. For-in loop (most common)4for (var number in numbers) {5 print(number);6}7 8// 2. Traditional for loop (when you need index)9for (int i = 0; i < numbers.length; i++) {10 print('Index $i: ${numbers[i]}');11}12 13// 3. forEach method14numbers.forEach((number) {15 print(number);16});17 18// 4. forEach with index using asMap()19numbers.asMap().forEach((index, value) {20 print('Index $index: $value');21});22 23// 5. While loop24int i = 0;25while (i < numbers.length) {26 print(numbers[i]);27 i++;28}29 30// Iterating with conditions31List<String> fruits = ['Apple', 'Banana', 'Cherry', 'Date'];32 33// Print only fruits starting with 'C'34for (var fruit in fruits) {35 if (fruit.startsWith('C')) {36 print(fruit); // Cherry37 }38}39 40// Using where to filter before iterating41fruits.where((fruit) => fruit.length > 5).forEach((fruit) {42 print(fruit); // Banana, Cherry43});HintUse for-in loops for simple iteration, traditional for loops when you need the index, and forEach() for functional-style programming.
List Transformation Methods
Dart provides powerful methods to transform lists without modifying the original list. These methods return new iterables or lists.
Map, Where, and Reduce
1List<int> numbers = [1, 2, 3, 4, 5];2 3// map() - Transform each element4List<int> doubled = numbers.map((n) => n * 2).toList();5print(doubled); // [2, 4, 6, 8, 10]6 7List<String> strings = numbers.map((n) => 'Number $n').toList();8print(strings); // [Number 1, Number 2, Number 3, Number 4, Number 5]9 10// where() - Filter elements11List<int> evenNumbers = numbers.where((n) => n % 2 == 0).toList();12print(evenNumbers); // [2, 4]13 14List<int> greaterThanTwo = numbers.where((n) => n > 2).toList();15print(greaterThanTwo); // [3, 4, 5]16 17// reduce() - Combine all elements into a single value18int sum = numbers.reduce((a, b) => a + b);19print(sum); // 1520 21int product = numbers.reduce((a, b) => a * b);22print(product); // 12023 24// fold() - Like reduce but with initial value25int sumPlusTen = numbers.fold(10, (prev, element) => prev + element);26print(sumPlusTen); // 25 (10 + 1 + 2 + 3 + 4 + 5)27 28// any() - Check if any element matches condition29bool hasEven = numbers.any((n) => n % 2 == 0);30print(hasEven); // true31 32// every() - Check if all elements match condition33bool allPositive = numbers.every((n) => n > 0);34print(allPositive); // true35 36// firstWhere() and lastWhere()37int firstEven = numbers.firstWhere((n) => n % 2 == 0);38print(firstEven); // 239 40int lastEven = numbers.lastWhere((n) => n % 2 == 0);41print(lastEven); // 442 43// Chaining methods44List<int> result = numbers45 .where((n) => n > 2) // Filter: [3, 4, 5]46 .map((n) => n * 2) // Transform: [6, 8, 10]47 .toList();48print(result); // [6, 8, 10]HintThese functional methods allow you to transform and filter lists in a clean, readable way. Remember to call toList() to convert the result back to a List.
Sorting and Reversing Lists
Dart provides methods to sort and reverse lists. These operations can modify the list in place or create a new sorted list.
Sorting and Reversing
1// Sorting numbers2List<int> numbers = [5, 2, 8, 1, 9, 3];3numbers.sort(); // Sorts in place4print(numbers); // [1, 2, 3, 5, 8, 9]5 6// Sorting in descending order7List<int> descending = [5, 2, 8, 1, 9, 3];8descending.sort((a, b) => b.compareTo(a));9print(descending); // [9, 8, 5, 3, 2, 1]10 11// Sorting strings12List<String> names = ['Charlie', 'Alice', 'Bob', 'David'];13names.sort();14print(names); // [Alice, Bob, Charlie, David]15 16// Case-insensitive sorting17List<String> words = ['apple', 'Banana', 'cherry', 'Date'];18words.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));19print(words); // [apple, Banana, cherry, Date]20 21// Sorting objects by property22class Person {23 String name;24 int age;25 Person(this.name, this.age);26}27 28List<Person> people = [29 Person('Alice', 30),30 Person('Bob', 25),31 Person('Charlie', 35),32];33 34people.sort((a, b) => a.age.compareTo(b.age));35people.forEach((p) => print('${p.name}: ${p.age}'));36// Bob: 2537// Alice: 3038// Charlie: 3539 40// Reversing a list41List<int> original = [1, 2, 3, 4, 5];42List<int> reversed = original.reversed.toList();43print(reversed); // [5, 4, 3, 2, 1]44print(original); // [1, 2, 3, 4, 5] (unchanged)45 46// Shuffle (randomize order)47import 'dart:math';48List<int> deck = [1, 2, 3, 4, 5];49deck.shuffle();50print(deck); // Random order, e.g., [3, 1, 5, 2, 4]HintUse sort() to modify the list in place, or reversed.toList() to create a new reversed list. Custom sorting is done with comparison functions.
Advanced List Operations
Explore advanced list operations including set operations, flattening, and working with nested lists.
Advanced Techniques
1// Removing duplicates (converting to Set and back)2List<int> withDuplicates = [1, 2, 2, 3, 3, 3, 4, 5, 5];3List<int> unique = withDuplicates.toSet().toList();4print(unique); // [1, 2, 3, 4, 5]5 6// Flattening nested lists7List<List<int>> nested = [[1, 2], [3, 4], [5, 6]];8List<int> flattened = nested.expand((list) => list).toList();9print(flattened); // [1, 2, 3, 4, 5, 6]10 11// Joining list elements into a string12List<String> words = ['Hello', 'World', 'Dart'];13String sentence = words.join(' ');14print(sentence); // "Hello World Dart"15 16List<int> numbers = [1, 2, 3, 4, 5];17String csv = numbers.join(', ');18print(csv); // "1, 2, 3, 4, 5"19 20// Splitting a list into chunks21List<int> data = [1, 2, 3, 4, 5, 6, 7, 8, 9];22List<List<int>> chunks = [];23int chunkSize = 3;24 25for (int i = 0; i < data.length; i += chunkSize) {26 int end = (i + chunkSize < data.length) ? i + chunkSize : data.length;27 chunks.add(data.sublist(i, end));28}29print(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]30 31// Finding min and max32List<int> scores = [85, 92, 78, 95, 88];33int maxScore = scores.reduce((a, b) => a > b ? a : b);34int minScore = scores.reduce((a, b) => a < b ? a : b);35print('Max: $maxScore, Min: $minScore'); // Max: 95, Min: 7836 37// Using reduce for max/min (alternative)38import 'dart:math';39int max = scores.reduce(max);40int min = scores.reduce(min);41print('Max: $max, Min: $min'); // Max: 95, Min: 7842 43// Zipping two lists together44List<String> names = ['Alice', 'Bob', 'Charlie'];45List<int> ages = [25, 30, 35];46 47List<Map<String, dynamic>> people = [];48for (int i = 0; i < names.length; i++) {49 people.add({'name': names[i], 'age': ages[i]});50}51print(people);52// [{name: Alice, age: 25}, {name: Bob, age: 30}, {name: Charlie, age: 35}]53 54// Taking and skipping elements55List<int> range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];56List<int> firstThree = range.take(3).toList();57print(firstThree); // [1, 2, 3]58 59List<int> skipFirstThree = range.skip(3).toList();60print(skipFirstThree); // [4, 5, 6, 7, 8, 9, 10]61 62List<int> middleElements = range.skip(2).take(5).toList();63print(middleElements); // [3, 4, 5, 6, 7]HintThese advanced operations help you manipulate lists in powerful ways. Use expand() for flattening, join() for creating strings, and take()/skip() for pagination.
Practical List Examples
Real-world scenarios demonstrating practical list usage in Dart applications.
Real-World List Operations
1// Shopping cart implementation2class CartItem {3 String name;4 double price;5 int quantity;6 7 CartItem(this.name, this.price, this.quantity);8 9 double get total => price * quantity;10}11 12List<CartItem> cart = [13 CartItem('Apple', 1.99, 3),14 CartItem('Banana', 0.99, 5),15 CartItem('Orange', 2.49, 2),16];17 18// Calculate total price19double totalPrice = cart.fold(0.0, (sum, item) => sum + item.total);20print('Total: $${totalPrice.toStringAsFixed(2)}'); // Total: $15.9021 22// Find expensive items (> $2)23List<CartItem> expensive = cart.where((item) => item.price > 2.0).toList();24expensive.forEach((item) => print(item.name)); // Orange25 26// Filter and search27List<String> products = [28 'iPhone 13',29 'iPad Pro',30 'MacBook Air',31 'AirPods Pro',32 'Apple Watch',33];34 35String searchTerm = 'pro';36List<String> searchResults = products37 .where((product) => product.toLowerCase().contains(searchTerm.toLowerCase()))38 .toList();39print(searchResults); // [iPad Pro, AirPods Pro]40 41// Pagination42List<int> allItems = List.generate(100, (i) => i + 1);43int pageSize = 10;44int currentPage = 2;45 46List<int> pageItems = allItems47 .skip((currentPage - 1) * pageSize)48 .take(pageSize)49 .toList();50print(pageItems); // [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]51 52// Grouping items53List<String> fruits = ['Apple', 'Apricot', 'Banana', 'Blueberry', 'Cherry'];54 55Map<String, List<String>> grouped = {};56for (var fruit in fruits) {57 String firstLetter = fruit[0];58 if (!grouped.containsKey(firstLetter)) {59 grouped[firstLetter] = [];60 }61 grouped[firstLetter]!.add(fruit);62}63print(grouped);64// {A: [Apple, Apricot], B: [Banana, Blueberry], C: [Cherry]}65 66// Top N items67List<int> scores = [85, 92, 78, 95, 88, 91, 76, 89];68List<int> topThree = (scores..sort((a, b) => b.compareTo(a))).take(3).toList();69print('Top 3 scores: $topThree'); // Top 3 scores: [95, 92, 91]70 71// Moving average calculation72List<double> prices = [10.5, 11.2, 10.8, 11.5, 12.0, 11.8];73int windowSize = 3;74 75List<double> movingAverages = [];76for (int i = 0; i <= prices.length - windowSize; i++) {77 double sum = prices.sublist(i, i + windowSize).reduce((a, b) => a + b);78 movingAverages.add(sum / windowSize);79}80print(movingAverages.map((avg) => avg.toStringAsFixed(2)));81// (10.83, 11.17, 11.43, 11.77)HintThese examples demonstrate common patterns like shopping carts, search functionality, pagination, grouping, and data analysis using lists.
Loot collected
Key takeaways- Lists are ordered, zero-indexed collections that can grow or shrink dynamically
- Use [] literal syntax for creating lists in most cases
- Access elements with [index], .first, .last, or .elementAt()
- Add elements with add(), addAll(), insert(), or insertAll()
- Remove elements with remove(), removeAt(), removeLast(), or removeWhere()
- Use map() to transform elements, where() to filter, and reduce() to combine
- Chain methods like where().map().toList() for complex transformations
- sort() modifies the list in place, reversed.toList() creates a new list
- Use expand() to flatten nested lists and join() to create strings
- Always check list bounds or use contains() before accessing elements
Side quests
Practice exercises
Exercise 1: Filter Even Numbers
Create a function that takes a list of integers and returns a new list containing only the even numbers.
Reveal solutionHide solution
1List<int> filterEvenNumbers(List<int> numbers) {2 return numbers.where((n) => n % 2 == 0).toList();3}4 5List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];6print(filterEvenNumbers(numbers)); // [2, 4, 6, 8, 10]Exercise 2: Calculate Average
Write a function that calculates the average of all numbers in a list.
Reveal solutionHide solution
1double calculateAverage(List<num> numbers) {2 if (numbers.isEmpty) return 0.0;3 num sum = numbers.reduce((a, b) => a + b);4 return sum / numbers.length;5}6 7List<int> scores = [85, 90, 78, 92, 88];8print(calculateAverage(scores).toStringAsFixed(2)); // "86.60"Exercise 3: Remove Duplicates
Create a function that removes duplicate elements from a list while preserving the original order.
Reveal solutionHide solution
1List<T> removeDuplicates<T>(List<T> list) {2 List<T> unique = [];3 Set<T> seen = {};4 5 for (var item in list) {6 if (!seen.contains(item)) {7 unique.add(item);8 seen.add(item);9 }10 }11 12 return unique;13}14 15List<int> numbers = [1, 2, 2, 3, 4, 3, 5, 1];16print(removeDuplicates(numbers)); // [1, 2, 3, 4, 5]Exercise 4: Find Second Largest
Write a function that finds the second largest number in a list.
Reveal solutionHide solution
1int? findSecondLargest(List<int> numbers) {2 if (numbers.length < 2) return null;3 4 List<int> sorted = numbers.toList()..sort((a, b) => b.compareTo(a));5 return sorted[1];6}7 8List<int> numbers = [10, 5, 8, 12, 3, 7];9print(findSecondLargest(numbers)); // 10Exercise 5: Chunk List
Create a function that splits a list into chunks of a specified size.
Reveal solutionHide solution
1List<List<T>> chunkList<T>(List<T> list, int chunkSize) {2 List<List<T>> chunks = [];3 4 for (int i = 0; i < list.length; i += chunkSize) {5 int end = (i + chunkSize < list.length) ? i + chunkSize : list.length;6 chunks.add(list.sublist(i, end));7 }8 9 return chunks;10}11 12List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];13print(chunkList(numbers, 3)); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]