List
A list is an ordered group of items. Flutter uses lists a lot, for example for the children of a column or the items on a screen.
dart
var names = <String>['Asha', 'Ravi', 'Meena'];
names.add('Kabir');
names.insert(0, 'Zoya');
names.remove('Ravi');
print(names.length); // 4
print(names[0]); // Zoya
print(names.first);
print(names.last);
print(names.contains('Asha')); // true
print(names.indexOf('Asha'));
Useful List Methods
dart
var nums = [5, 3, 8, 1];
print(nums.map((n) => n * 2).toList()); // [10, 6, 16, 2]
print(nums.where((n) => n > 3).toList()); // [5, 8]
print(nums.reduce((a, b) => a + b)); // 17
print(nums.any((n) => n > 7)); // true
print(nums.every((n) => n > 0)); // true
print(nums.firstWhere((n) => n > 5)); // 8
nums.sort(); // [1, 3, 5, 8]
nums.sort((a, b) => b.compareTo(a)); // [8, 5, 3, 1]
Set
A set holds unique items and has no fixed order.
dart
var tags = <String>{'dart', 'flutter', 'dart'};
print(tags); // {dart, flutter}
tags.add('mobile');
print(tags.contains('flutter'));
Map
A map stores values by key, like a dictionary. JSON data from the internet becomes a Map in Dart.
dart
var user = <String, dynamic>{
'name': 'Asha',
'age': 25,
'city': 'Pune',
};
print(user['name']); // Asha
user['age'] = 26;
user['email'] = 'asha@example.com';
user.remove('city');
for (final entry in user.entries) {
print('${entry.key}: ${entry.value}');
}
| Collection | Ordered? | Duplicates? | Access by |
| List | Yes | Allowed | Index |
| Set | No | Not allowed | Value |
| Map | Insertion order | Keys are unique | Key |
Spread Operator and Collection if / for
These special features make building widget lists in Flutter easy.
dart
var a = [1, 2];
var b = [0, ...a, 3]; // [0, 1, 2, 3]
bool isAdmin = true;
var menu = [
'Home',
'Profile',
if (isAdmin) 'Admin Panel', // collection if
];
var labels = [
for (var i = 1; i <= 3; i++) 'Item $i', // collection for
];
In Flutter: You will write children: [Text('A'), if (loggedIn) Text('Welcome'), ...otherWidgets] all the time.
Conclusion
Lists, sets and maps cover almost every data need. The methods map, where and sort turn many loops into a single readable line.
Quick Summary: List is ordered, Set is unique and Map uses keys. Use map, where and the spread operator for clean code.