Lists

Perhaps the most common collection in nearly every programming languageis the array, or ordered group of objects. In Dart, arrays areList objects, so most people just call them lists.

Dart list literals look like JavaScript array literals. Here’s a simpleDart list:

  1. var list = [1, 2, 3];

Note: Dart infers that list 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 type inference.

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:

  1. var list = [1, 2, 3];
  2. assert(list.length == 3);
  3. assert(list[1] == 2);
  4. list[1] = 1;
  5. assert(list[1] == 1);

To create a list that’s a compile-time constant,add const before the list literal:

  1. var constantList = const [1, 2, 3];
  2. // constantList[1] = 1; // Uncommenting this causes an error.

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:

  1. var list = [1, 2, 3];
  2. var list2 = [0, ...list];
  3. 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 (…?):

  1. var list;
  2. var list2 = [0, ...?list];
  3. assert(list2.length == 1);

For more details and examples of using the spread operator, see thespread operator proposal.

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:

  1. var nav = [
  2. 'Home',
  3. 'Furniture',
  4. 'Plants',
  5. if (promoActive) 'Outlet'
  6. ];

Here’s an example of using collection forto manipulate the items of a list beforeadding them to another list:

  1. var listOfInts = [1, 2, 3];
  2. var listOfStrings = [
  3. '#0',
  4. for (var i in listOfInts) '#$i'
  5. ];
  6. assert(listOfStrings[1] == '#1');

For more details and examples of using collection if and for, see thecontrol flow collections proposal.

The List type has many handy methods for manipulating lists. For moreinformation about lists, see Generics andCollections.