Dart Collection Types
A collection is a data structure used to hold multiple pieces of data.
Dart has three built-in core collection types: List (list), Set (set), and Map (map); this chapter introduces their usage one by one.
List: ordered list
List is the most commonly used collection type, used to hold a group of ordered elements, allowing duplicates.
You can access any element in a List by index (starting from 0).
Creating a List
Example
void
main
(
)
{
// Create a List using a literal
List
<
String
sites
=
[
'RUNOOB'
,
'Google'
,
'GitHub'
];
(
'Website list: $sites'
)
;
// Type inference (omit generics)
var
numbers
=
[
1
,
2
,
3
,
4
,
5
]
;
(
'Number list: $numbers'
)
;
// Create an empty list
var
emptyList
=
<
String
[
];
// Use List.filled to create a fixed-length list
var
zeros
=
List.
filled
(
3
,
0
)
;
// [0, 0, 0]
(
'Filled list: $zeros'
)
;
// Use List.generate to generate a list
var
squares
=
List.
generate
(
5
,
(
i
)
=>
i
i
)
;
(
'Square-number list: $squares'
)
;
}
网站列表: [RUNOOB, Google, GitHub]
数字列表: [1, 2, 3, 4, 5]
填充列表: [0, 0, 0]
平方数列表: [0, 1, 4, 9, 16]
Accessing and Modifying List Elements
Example
void
main
(
)
{
var
fruits
=
[
'Apple'
,
'Banana'
,
'Orange'
]
;
// Access by index (starting from 0)
(
'First fruit: ${fruits[0]}'
)
;
// Apple
(
'The last one: ${fruits[fruits.length - 1]}'
)
;
// Orange
// Modify an element
fruits
[
1
]
=
'Grape'
;
(
'After modification: $fruits'
)
;
// [Apple, Grape, Orange]
// Get the length
(
'Number of fruits: ${fruits.length}'
)
;
// Check whether it is empty
(
'Is the list empty? ${fruits.isEmpty}'
)
;
(
'Is the list not empty? ${fruits.isNotEmpty}'
)
;
}
第一个水果: 苹果
最后一个: 橙子
修改后: [苹果, 葡萄, 橙子]
水果数量: 3
列表为空? false
列表非空? true
Common List Operations
Example
void
main
(
)
{
var
list
=
[
'RUNOOB'
,
'Dart'
]
;
// Add elements
list.
add
(
'Flutter'
)
;
// Add a single one
list.
addAll
(
[
'Google'
,
'AI'
]
)
;
// Add multiple
(
'After adding: $list'
)
;
// Insert an element (at a specified position)
list.
insert
(
1
,
'Tutorial'
)
;
(
'After insertion: $list'
)
;
// Delete elements
list.
remove
(
'AI'
)
;
// Remove by value
list.
removeAt
(
0
)
;
// Remove by index
list.
removeLast
(
)
;
// Remove the last one
(
'After removal: $list'
)
;
// Find element
bool
hasDart
=
list.
contains
(
'Dart'
)
;
int
index
=
list.
indexOf
(
'Dart'
)
;
(
'Contains Dart? $hasDart, position: $index'
)
;
// Sort
var
nums
=
[
3
,
1
,
4
,
1
,
5
,
9
]
;
nums.
sort
(
)
;
(
'After sorting: $nums'
)
;
// Reverse
var
reversed
=
nums.
reversed
.
toList
(
)
;
(
'After reversing: $reversed'
)
;
// Take a sublist
var
subList
=
nums.
sublist
(
0
,
3
)
;
(
'First 3: $subList'
)
;
}
添加后: [RUNOOB, Dart, Flutter, Google, AI]
插入后: [RUNOOB, 教程, Dart, Flutter, Google, AI]
删除后: [教程, Dart, Flutter]
包含 Dart? true, 位置: 1
排序后: [1, 1, 3, 4, 5, 9]
反转后: [9, 5, 4, 3, 1, 1]
前3个: [1, 1, 3]
Functional Methods of List
Dart's List supports functional methods such as map, where, and reduce, making data processing more concise.
Example
void
main
(
)
{
var
scores
=
[
55
,
78
,
92
,
60
,
45
,
88
]
;
// where: filter (keep elements satisfying the condition)
var
passed
=
scores.
where
(
(
s
)
=>
s
=
60
)
;
(
'Passing scores: $passed'
)
;
// map: map (transform each element into a new value)
var
grades
=
scores.
map
(
(
s
)
=>
s
=
60
?
'Pass'
:
'Fail'
)
;
(
'Grades: $grades'
)
;
// where + map chaining
var
highScores
=
scores
.
where
(
(
s
)
=>
s
=
80
)
.
map
(
(
s
)
=>
'High score: $s'
)
.
toList
(
)
;
(
'High-score list: $highScores'
)
;
// reduce: cumulative computation
var
total
=
scores.
reduce
(
(
sum
,
s
)
=>
sum
s
)
;
(
'RUNOOB total score: $total'
)
;
// fold: cumulative computation with an initial value
var
avg
=
scores.
fold
(
0
,
(
sum
,
s
)
=>
sum
s
)
/
scores.
length
;
(
'Average score: ${avg.toStringAsFixed(1)}'
)
;
// any / every: existence checks
bool
hasFullMark
=
scores.
any
(
(
s
)
=>
s
==
100
)
;
bool
allPassed
=
scores.
every
(
(
s
)
=>
s
=
60
)
;
(
'Is there a full mark? $hasFullMark'
)
;
(
'All passed? $allPassed'
)
;
}
及格分数: (78, 92, 60, 88)
评级: (不及格, 及格, 及格, 及格, 不及格, 及格)
高分列表: [高分: 92, 高分: 88]
RUNOOB 总分: 418
平均分: 69.7
有满分吗? false
全部及格? false
map() and where() return an Iterable (lazy evaluation); you need to convert it to a List with toList() for the computation to actually execute. If you only need to iterate once, just use the Iterable directly, no conversion needed.
Set: collection of unique elements
Set is similar to List, but each element in a Set can appear only once; duplicates are not allowed.
Set is unordered; elements cannot be accessed by index.
Example
void
main
(
)
{
// Create a Set (elements are automatically deduplicated)
Set
<
String
tags
=
{
'Dart'
,
'Flutter'
,
'Dart'
,
'RUNOOB'
};
(
'Tag set: $tags'
)
;
// {Dart, Flutter, RUNOOB}, the duplicate Dart was removed
(
'Number of tags: ${tags.length}'
)
;
// 3
// Add elements
tags.
add
(
'Google'
)
;
tags.
add
(
'Dart'
)
;
// Dart already exists, so it will not be added again
(
'After adding: $tags'
)
;
// Delete elements
tags.
remove
(
'Google'
)
;
(
'After removal: $tags'
)
;
// Check whether it contains
(
'Contains RUNOOB? ${tags.contains('
RUNOOB
')}'
)
;
// Set operations
var
setA
=
{
1
,
2
,
3
,
4
}
;
var
setB
=
{
3
,
4
,
5
,
6
}
;
(
'Intersection: ${setA.intersection(setB)}'
)
;
// {3, 4}
(
'Union: ${setA.union(setB)}'
)
;
// {1, 2, 3, 4, 5, 6}
(
'Difference: ${setA.difference(setB)}'
)
;
// {1, 2}
}
标签集合: {Dart, Flutter, RUNOOB}
标签数量: 3
添加后: {Dart, Flutter, RUNOOB, Google}
删除后: {Dart, Flutter, RUNOOB}
包含 RUNOOB? true
交集: {3, 4}
并集: {1, 2, 3, 4, 5, 6}
差集: {1, 2}
The typical use case for Set is "deduplication" - when you do not need duplicate elements, using a Set is far more efficient than manually deduplicating with a List.
Map: key-value mapping
Map is used to store key-value pairs (Key-Value Pair); each key maps to one value.
Keys must be unique in a Map, while values may repeat.
Creating and Accessing a Map
Example
void
main
(
)
{
// Create a Map using a literal
Map
<
String
,
String
siteInfo
=
{
'name':
'RUNOOB'
,
'url'
:
'https://www.runoob.com'
,
'type'
:
'Programming Tutorial'
,
}
;
// Access a value by key
(
'Site name: ${siteInfo['
name
']}'
)
;
(
'Site URL: ${siteInfo['
url
']}'
)
;
// Accessing a non-existent key returns null
(
'Description: ${siteInfo['
description
']}'
)
;
// null
// Add/modify a key-value pair
siteInfo
[
'language'
]
=
'Chinese'
;
siteInfo
[
'name'
]
=
'RUNOOB.COM'
;
// Modify the value of an existing key
(
'After update: $siteInfo'
)
;
// Get all keys and all values
(
'All keys: ${siteInfo.keys}'
)
;
(
'All values: ${siteInfo.values}'
)
;
// Check whether a key exists
(
'Has url key? ${siteInfo.containsKey('
url
')}'
)
;
(
'Has desc key? ${siteInfo.containsKey('
desc
')}'
)
;
}
站点名称: RUNOOB
站点 URL: https://www.runoob.com
描述: null
更新后: {name: RUNOOB.COM, url: https://www.runoob.com, type: 编程教程, language: 中文}
所有键: (name, url, type, language)
所有值: (RUNOOB.COM, https://www.runoob.com, 编程教程, 中文)
有 url 键? true
有 desc 键? false
Common Map Operations
Example
void
main
(
)
{
var
scores
=
{
'runoob'
:
95
,
'Alice'
:
87
,
'Bob'
:
72
,
}
;
// Iterate over a Map
scores.
forEach
(
(
name
,
score
)
{
(
'$name: $score points'
)
;
}
)
;
// Delete a key-value pair
scores.
remove
(
'Bob'
)
;
(
'After deleting Bob: $scores'
)
;
// Get a value or a default value
int
aliceScore
=
scores
[
'Alice'
]
??
0
;
int
eveScore
=
scores
[
'Eve'
]
??
0
;
// Does not exist, return the default value 0
(
'Alice: $aliceScore, Eve: $eveScore'
)
;
// putIfAbsent: add only when the key does not exist
scores.
putIfAbsent
(
'runoob'
,
(
)
=>
100
)
;
// Already exists, do not add
scores.
putIfAbsent
(
'David'
,
(
)
=>
80
)
;
// Does not exist, add it
(
'Final: $scores'
)
;
// Get the length
(
'Number of people: ${scores.length}'
)
;
}
runoob: 95 分
Alice: 87 分
Bob: 72 分
删除 Bob 后: {runoob: 95, Alice: 87}
Alice: 87, Eve: 0
最终: {runoob: 95, Alice: 87, David: 80}
人数: 3
Map keys can be of any type (String, int, etc.), but key equality must be meaningful. When using a custom object as a key, make sure == and hashCode are correctly implemented.
Collection spread operators ... and ...?
The spread operator can "spread" the elements of one collection into another.
Example
void
main
(
)
{
var
basics
=
[
'Dart'
,
'Flutter'
]
;
var
advanced
=
[
'Asynchronous Programming'
,
'State Management'
]
;
// ... spread operator: insert the elements of another collection
var
allCourses
=
[
'RUNOOB Getting Started'
,
..
.
basics
,
..
.
advanced
]
;
(
'All courses: $allCourses'
)
;
// ...? null-aware spread: if the collection is null, skip it
List
<
String
?
optionalList;
// May be null
var
safeList
=
[
'First Item'
,
..
.
?
optionalList
]
;
(
'Safe spread: $safeList'
)
;
// Only the first item
optionalList
=
[
'Extra content'
]
;
safeList
=
[
'First Item'
,
..
.
?
optionalList
]
;
(
'Spread with value: $safeList'
)
;
}
所有课程: [RUNOOB 入门, Dart, Flutter, 异步编程, 状态管理]
安全展开: [第一项]
有值展开: [第一项, 额外内容]
if and for in Collections (Collection Control Flow)
Dart allows using if and for directly inside collection literals, which is very practical syntactic sugar.
Example
void
main
(
)
{
bool
showAdmin
=
true
;
// if in a collection: decide whether to include an element based on a condition
var
menuItems
=
[
'Home'
,
'Tutorial'
,
if
(
showAdmin
)
'Admin Backend'
,
// Only added when the condition is true
'About'
,
]
;
(
'Menu: $menuItems'
)
;
// for in a collection: generate elements from another collection
var
numbers
=
[
1
,
2
,
3
]
;
var
doubled
=
[
for
(
var
n
in
numbers
)
n
2
,
// Iterate to generate new elements
]
;
(
'Doubled: $doubled'
)
;
// if + for can be combined
var
tags
=
[
'Dart'
,
'Flutter'
]
;
var
links
=
[
'RUNOOB Home'
,
for
(
var
tag
in
tags
)
'https://runoob.com/$tag'
,
]
;
(
'Links: $links'
)
;
}
菜单: [首页, 教程, 管理后台, 关于]
翻倍: [2, 4, 6]
链接: [RUNOOB 首页, https://runoob.com/Dart, https://runoob.com/Flutter]
Comparison of the Three Collection Types
| Feature | List | Set | Map |
|---|---|---|---|
| Ordering | Ordered | Unordered | Unordered (but has an iteration order) |
| Duplicates allowed | Allowed | Not allowed | Keys cannot repeat, values can |
| Index access | Supports [] | Not supported | Access by key [] |
| Typical scenario | Ordered lists, sequences | Deduplication, tag sets | Key-value mapping, configuration items |
| Creating Literals | [] | {} | {key: value} |
Notes
Both Set and Map use {} as their literal.
The difference is:
- Map uses the key: value form (with a colon)
- Set writes elements directly (no colon)
For example:
var map = {'name': 'Tom'}; // Map
var set = {'Tom', 'Jerry'}; // Set
One thing to note in particular:
var x = {};
This does not create an empty Set; Dart will infer it as:
Map
Because empty braces cannot reveal the element type, Dart treats it as a Map by default.
To create an empty Set, you must specify it explicitly:
var x = {};
or
:
Set x = {};