Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

dart.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.

Learn more
Collections

Dart 3.10 is taking off with dot shorthands, stable build hooks, nuanced deprecation annotations, and more!Learn more

Dart has built-in support for list, set, and mapcollections. To learn more about configuring the types collections contain, check outGenerics.

Lists

#

Perhaps the most common collection in nearly every programming language is thearray, or ordered group of objects. In Dart, arrays areList objects, so most people just call themlists.

Dart list literals are denoted by a comma-separated list of elements enclosed in square brackets ([]). Each element is usually an expression. Here's a simple Dart list:

dart
varlist=[1,2,3];
Note

You can add a comma after the last item in a Dart collection literal. Thistrailing comma doesn't affect the collection, but it can help prevent copy-paste errors.

dart
varlist=['Car','Boat','Plane'];

Lists use zero-based indexing, where 0 is the index of the first element andlist.length - 1 is the index of the last element. You can get a list's length using the.length property and access a list's elements using the subscript operator ([]):

dart
varlist=[1,2,3];assert(list.length==3);assert(list[1]==2);list[1]=1;assert(list[1]==1);

To create a list that's a compile-time constant, addconst before the list literal:

dart
varconstantList=const[1,2,3];// constantList[1] = 1; // This line will cause an error.

For more information about lists, refer to the Lists section of thedart:core documentation.

Sets

#

A set in Dart is an unordered collection of unique elements. Dart support for sets is provided by set literals and theSet type.

Here is a simple Dart set, created using a set literal:

dart
varhalogens={'fluorine','chlorine','bromine','iodine','astatine'};
Note

To create an empty set, use{} preceded by a type argument, or assign{} to a variable of typeSet:

dart
varnames=<String>{};// Set<String> names = {}; // This works, too.// var names = {}; // Creates a map, not a set.
Set or map?

The syntax for map literals is similar to that for set literals. Because map literals came first,{} defaults to theMap type. If you forget the type annotation on{} or the variable it's assigned to, then Dart creates an object of typeMap<dynamic, dynamic>.

Add items to an existing set using theadd() oraddAll() methods:

dart
varelements=<String>{};elements.add('fluorine');elements.addAll(halogens);

Use.length to get the number of items in the set:

dart
varelements=<String>{};elements.add('fluorine');elements.addAll(halogens);assert(elements.length==5);

To create a set that's a compile-time constant, addconst before the set literal:

dart
finalconstantSet=const{'fluorine','chlorine','bromine','iodine','astatine',};// constantSet.add('helium'); // This line will cause an error.

For more information about sets, refer to the Sets section of thedart:core documentation.

Maps

#

In a map, each element is a key-value pair. Each key within a pair is associated with a value, and both keys and values can be any type of object. Each key can occur only once, although the same value can be associated with multiple different keys. Dart support for maps is provided by map literals and theMap type.

Here are a couple of simple Dart maps, created using map literals:

dart
vargifts={// Key:    Value'first':'partridge','second':'turtledoves','fifth':'golden rings',};varnobleGases={2:'helium',10:'neon',18:'argon'};
Note

You can create the same objects using a Map constructor:

dart
vargifts=Map<String,String>();gifts['first']='partridge';gifts['second']='turtledoves';gifts['fifth']='golden rings';varnobleGases=Map<int,String>();nobleGases[2]='helium';nobleGases[10]='neon';nobleGases[18]='argon';
Note

Add a new key-value pair to an existing map using the subscript assignment operator ([]=):

dart
vargifts={'first':'partridge'};gifts['fourth']='calling birds';// Add a key-value pair

Retrieve a value from a map using the subscript operator ([]):

dart
vargifts={'first':'partridge'};assert(gifts['first']=='partridge');

If you look for a key that isn't in a map, you getnull in return:

dart
vargifts={'first':'partridge'};assert(gifts['fifth']==null);

Use.length to get the number of key-value pairs in the map:

dart
vargifts={'first':'partridge'};gifts['fourth']='calling birds';assert(gifts.length==2);

To create a map that's a compile-time constant, addconst before the map literal:

dart
finalconstantMap=const{2:'helium',10:'neon',18:'argon'};// constantMap[2] = 'Helium'; // This line will cause an error.

For more information about maps, refer to the Maps section of thedart:core documentation.

Collection elements

#

A collection literal contains a series of elements. During runtime, each element is evaluated, producing zero or more values that are then inserted into the resulting collection. These elements fall into two main categories: leaf elements and control flow elements.

  • Leaf element: Inserts an individual item into a collection literal.

    • Expression element: Evaluates a single expression and inserts the resulting value into the collection.

    • Map entry element: Evaluates a pair of key and value expressions and inserts the resulting entry into the collection.

  • Control flow element: Conditionally or iteratively adds zero or more values to the surrounding collection.

    • Null-aware element: Evaluates an expression and if the result is notnull, inserts the value into the surrounding collection.

    • Spread element: Iterates over a given sequence (collection expression) and inserts all of the resulting values into the surrounding collection.

    • Null-aware spread element: Similar to the spread element, but allows the collection to benull and inserts nothing if it is.

    • If element: Conditionally evaluates an inner element based on given a condition expression, and optionally evaluates anotherelse element if the condition is false.

    • For element: Iterates and repeatedly evaluates a given inner element, inserting zero or more resulting values.

To learn more about collection elements, see the following sections.

Expression elements

#

An expression element evaluates a single expression and inserts the resulting value into a collection. This expression can encompass various constructs like literals, variables, operators, function calls, and constructor calls.

An expression element has this syntax in a collection:

dart
<expression>

Map entry elements

#

A map entry element evaluates a pair of key and value expressions and inserts the resulting entry into a collection. Both the key and the value within this pair can be expressions.

A map entry element has this syntax in a collection:

dart
<key_expression>:<value_expression>

Null-aware elements

#

A null-aware element evaluates an expression and if the result is notnull, inserts the value into the surrounding collection.

Version note

A null-aware element has the following syntax in an expression element:

dart
?<expression>

A null-aware element has the following syntax in a map entry element:

dart
// key is a null-aware element?<key_expression>:<value_expression>
dart
// value is a null-aware element<key_expression>:?<value_expression>
dart
// key and value are null-aware elements?<key_expression>:?<value_expression>

In the following example, the result for the null-aware element?a is not added to a list calleditems becausea isnull:

dart
int?absentValue=null;int?presentValue=3;varitems=[1,?absentValue,?presentValue,absentValue,5,];// [1, 3, null, 5]

The following example illustrates various ways that you can use null-aware elements inside of map entry elements:

dart
String?presentKey='Apple';String?absentKey=null;int?presentValue=3;int?absentValue=null;varitemsA={presentKey:absentValue};// {Apple: null}varitemsB={presentKey:?absentValue};// {}varitemsC={absentKey:presentValue};// {null: 3}varitemsD={?absentKey:presentValue};// {}varitemsE={absentKey:absentValue};// {null: null}varitemsF={?absentKey:?absentValue};// {}

Spread elements

#

The spread element iterates over a given sequence and inserts all of the resulting values into the surrounding collection.

A spread element has the following syntax in a collection. The sequence expression can represent any expression that evaluates to an object that implementsIterable:

dart
...<sequence_expression>

In the following example, the elements in a list calleda are added to a list calleditems.

dart
vara=[1,2,null,4];varitems=[0,...a,5];// [0, 1, 2, null, 4, 5]

If you are spreading an expression that might evaluate tonull and you want to ignore thenull (and insert no elements), use anull-aware spread element.

To learn more about the spread operator, seeSpread operator.

Null-aware spread elements

#

The null-aware spread element is similar to the spread element, but allows the collection to benull and inserts nothing if it is.

A null-aware spread element has this syntax in a collection:

dart
...?<sequence_expression>

In the following example, a list calleda is ignored because it's null, but the elements in a list calledb are added to a list calleditems. Notice that if a collection itself is notnull, but it contains elements that are, thosenull elements are still added to the result.

dart
List<int>?a=null;varb=[1,null,3];varitems=[0,...?a,...?b,4];// [0, 1, null, 3, 4]

Because of null safety, you can't perform a spread operation (...) on a value that might be null. The following example produces a compile-time error because theextraOptions parameter is nullable and the spread operator used onextraOptions is not null-aware.

static analysis: failuredart
List<String>buildCommandLine(Stringexecutable,List<String>options,[List<String>?extraOptions,]){return[executable,...options,...extraOptions,// <-- Error];}// Usage://   buildCommandLine('dart', ['run', 'my_script.dart'], null);// Result://   Compile-time error

If you want to spread a nullable collection, use a null-aware spread element. The following example is valid because the null-aware spread operator is used onextraOptions.

dart
List<String>buildCommandLine(Stringexecutable,List<String>options,[List<String>?extraOptions,]){return[executable,...options,...?extraOptions,// <-- OK now.];}// Usage://   buildCommandLine('dart', ['run', 'my_script.dart'], null);// Result://   [dart, run, my_script.dart]

To learn more about the null-aware spread operator, seeSpread operator.

If elements

#

Anif element conditionally evaluates an inner element based on given a condition expression, and optionally evaluates anotherelse element if the condition is false.

Theif element has a few syntax variations:

dart
// If the bool expression is true, include the result.if(<bool_expression>)<result>
dart
// If the expression matches the pattern, include the result.if(<expression>case<pattern>)<result>
dart
// If the operation resolves as true, include the first// result, otherwise, include the second result.if(<bool_expression>)<result>else<result>
dart
// If the operation resolves as true, include the first// result, otherwise, include the second result.if(<expression>case<pattern>)<result>else<result>

The following examples illustrate various ways that you can use anif element inside of a collection with a boolean expression:

dart
varincludeItem=true;varitems=[0,if(includeItem)1,2,3];// [0, 1, 2, 3]
dart
varincludeItem=true;varitems=[0,if(!includeItem)1,2,3];// [0, 2, 3]
dart
varname='apple';varitems=[0,if(name=='orange')1else10,2,3];// [0, 10, 2, 3]
dart
varname='apple';varitems=[0,if(name=='kiwi')1elseif(name=='pear')10,2,3,];// [0, 2, 3]

The following examples illustrate various ways that you can use anif element with acase part inside of a collection:

dart
Objectdata=123;vartypeInfo=[if(datacaseinti)'Data is an integer:$i',if(datacaseStrings)'Data is a string:$s',if(datacaseboolb)'Data is a boolean:$b',if(datacasedoubled)'Data is a double:$d',];// [Data is an integer: 123, Data is a double: 123]
dart
varword='hello';varitems=[1,if(wordcaseString(length:varwordLength))wordLength,3,];// [1, 5, 3]
dart
varorderDetails=['Apples',12,''];varsummary=['Product:${orderDetails[0]}',if(orderDetailscase[_,intqty,_])'Quantity:$qty',if(orderDetailscase[_,_,''])'Delivery: Not Started'else'Delivery: In Progress',];// [Product: Apples, Quantity: 12, Delivery: Not Started]

You can mix differentif operations with anelse if part. For example:

dart
vara='apple';varb='orange';varc='mango';varitems=[0,if(a=='apple')1elseif(acase'mango')10,if(bcase'pear')2elseif(b=='mango')20,if(ccase'apple')3elseif(ccase'mango')30,4,];// [0, 1, 30, 4]

To learn more about theif conditional, seeif statement. To learn more about theif-case conditional, seeif-case statement.

For elements

#

Afor element iterates and repeatedly evaluates a given inner element, inserting zero or more resulting values.

Afor element has this syntax in a collection:

dart
for(<expression>in<collection>)<result>
dart
for(<initialization_clause>;<condition_clause>;<increment_clause>)<result>

The following examples illustrate various ways that you can use afor element inside of a collection:

dart
varnumbers=[2,3,4];varitems=[1,for(varninnumbers)n*n,7];// [1, 4, 9, 16, 7]
dart
varitems=[1,for(varx=5;x>2;x--)x,7];// [1, 5, 4, 3, 7]
dart
varitems=[1,for(varx=2;x<4;x++)x,7];// [1, 2, 3, 7]

To learn more about thefor loop, seefor loops.

Nest control flow elements

#

You can nest control flow elements within each other. This is a powerful alternative to list comprehensions in other languages.

In the following example, only the even numbers innumbers are included initems.

dart
varnumbers=[1,2,3,4,5,6,7];varitems=[0,for(varninnumbers)if(n.isEven)n,8,];// [0, 2, 4, 6, 8]

It's common and idiomatic to use a spread on a collection literal immediately inside of anif orfor element. For example:

dart
varitems=[if(condition)oneThing(),if(condition)...[multiple(),things()],];// [oneThing, [multiple_a, multiple_b], things]

You can nest all kinds of elements arbitrarily deep. In the following example,if,for and spread elements are nested within each other in a collection:

dart
varnestItems=true;varys=[1,2,3,4];varitems=[if(nestItems)...[for(varx=0;x<3;x++)for(varyinys)if(x<y)x+y*10,],];// [10, 20, 30, 40, 21, 31, 41, 32, 42]
Was this page's content helpful?

Unless stated otherwise, the documentation on this site reflects Dart 3.10.0. Page last updated on 2025-6-18.View source orreport an issue.


[8]ページ先頭

©2009-2025 Movatter.jp