Arrays in Dart

Our first program will demonstrate how to work with arrays in Dart. Here’s the full source code with explanations:

void main() {
  // Here we create a List (Dart's equivalent of an array) that will hold exactly
  // 5 integers. By default, a List is filled with null values.
  var a = List<int>.filled(5, 0);
  print('emp: $a');

  // We can set a value at an index using the list[index] = value syntax,
  // and get a value with list[index].
  a[4] = 100;
  print('set: $a');
  print('get: ${a[4]}');

  // The length property returns the length of a List.
  print('len: ${a.length}');

  // Use this syntax to declare and initialize a List in one line.
  var b = [1, 2, 3, 4, 5];
  print('dcl: $b');

  // In Dart, we don't need to specify the length when initializing a List.
  // The spread operator (...) can be used to insert all elements from one list into another.
  var c = [...b];
  print('spread: $c');

  // If you want to create a List with specific indexes filled and others empty,
  // you can use the List.generate constructor.
  var d = List<int>.generate(5, (index) => index == 0 ? 100 : (index == 3 ? 400 : 0));
  print('idx: $d');

  // List types are one-dimensional, but you can create multi-dimensional
  // data structures using Lists of Lists.
  var twoD = List.generate(2, (_) => List.filled(3, 0));
  for (var i = 0; i < 2; i++) {
    for (var j = 0; j < 3; j++) {
      twoD[i][j] = i + j;
    }
  }
  print('2d: $twoD');

  // You can create and initialize multi-dimensional Lists at once too.
  twoD = [
    [1, 2, 3],
    [1, 2, 3],
  ];
  print('2d: $twoD');
}

To run the program, save it as arrays.dart and use the dart command:

$ dart arrays.dart
emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
spread: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 0]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]

Note that Lists in Dart are displayed in the form [v1, v2, v3, ...] when printed.

In Dart, we use Lists instead of arrays. Lists are more flexible and can be resized dynamically. The List<int> syntax specifies a List that contains integers.

Dart doesn’t have a direct equivalent to Go’s [...]int{1, 2, 3} syntax for creating arrays with inferred length. Instead, we can simply use [1, 2, 3] to create a List.

For creating Lists with specific indexes filled and others empty, we use List.generate constructor instead of Go’s index specification syntax.

Multi-dimensional data structures in Dart are created using Lists of Lists, similar to how it’s done in many other languages.