Dart list literals look like JavaScript array literals. Here’s a simpleDart list:
Note: Dart infers that has type List<int>
. If you try to add non-integer objects to this list, the analyzer or runtime raises an error. For more information, read about
Lists use zero-based indexing, where 0 is the index of the first elementand list.length - 1
is the index of the last element. You can get alist’s length and refer to list elements just as you would inJavaScript:
var list = [1, 2, 3];
assert(list.length == 3);
assert(list[1] == 2);
Dart 2.3 introduced the spread operator (…
) and thenull-aware spread operator (…?
),which provide a concise way to insert multiple elements into a collection.
For example, you can use the spread operator (…
) to insertall the elements of a list into another list:
var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);
If the expression to the right of the spread operator might be null,you can avoid exceptions by using a null-aware spread operator ():
Dart 2.3 also introduced collection if and collection for,which you can use to build collections using conditionals (if
)and repetition (for
).
Here’s an example of using collection ifto create a list with three or four items in it:
'Home',
'Furniture',
'Plants',
if (promoActive) 'Outlet'
Here’s an example of using collection forto manipulate the items of a list beforeadding them to another list:
The List type has many handy methods for manipulating lists. For moreinformation about lists, see Generics and.