Slices in Dart

Lists in Dart are an important data type, providing a powerful interface to sequences. They are similar to arrays in other languages but offer more flexibility and functionality.

import 'dart:core';

void main() {
  // Unlike arrays, lists in Dart are dynamically sized.
  // An uninitialized list is equal to null and has length 0.
  List<String>? s;
  print("uninit: $s ${s == null} ${s?.length == 0}");

  // To create an empty list with non-zero length, we can use
  // the List constructor. Here we create a list of strings
  // with length 3 (initially filled with null values).
  s = List<String>.filled(3, '');
  print("emp: $s len: ${s.length} cap: ${s.length}");

  // We can set and get elements just like with arrays.
  s[0] = "a";
  s[1] = "b";
  s[2] = "c";
  print("set: $s");
  print("get: ${s[2]}");

  // length returns the length of the list as expected.
  print("len: ${s.length}");

  // Lists in Dart can be easily expanded using the add method.
  s.add("d");
  s.addAll(["e", "f"]);
  print("apd: $s");

  // We can create a copy of a list using the spread operator.
  var c = [...s];
  print("cpy: $c");

  // Lists support slicing with the sublist method.
  var l = s.sublist(2, 5);
  print("sl1: $l");

  // This slices up to (but excluding) index 5.
  l = s.sublist(0, 5);
  print("sl2: $l");

  // And this slices from (and including) index 2 to the end.
  l = s.sublist(2);
  print("sl3: $l");

  // We can declare and initialize a list in a single line as well.
  var t = ["g", "h", "i"];
  print("dcl: $t");

  // Dart provides various utility methods for lists.
  var t2 = ["g", "h", "i"];
  if (listEquals(t, t2)) {
    print("t == t2");
  }

  // Lists can be composed into multi-dimensional data structures.
  // The length of the inner lists can vary.
  var twoD = List.generate(3, (i) => List.generate(i + 1, (j) => i + j));
  print("2d: $twoD");
}

// A simple implementation of listEquals for demonstration
bool listEquals<T>(List<T> a, List<T> b) {
  if (a.length != b.length) return false;
  for (var i = 0; i < a.length; i++) {
    if (a[i] != b[i]) return false;
  }
  return true;
}

Note that while lists in Dart are different from arrays in some languages, they are rendered similarly when printed.

To run this Dart program, save it as lists.dart and use the dart command:

$ dart run lists.dart
uninit: null true true
emp: [, , ] len: 3 cap: 3
set: [a, b, c]
get: c
len: 3
apd: [a, b, c, d, e, f]
cpy: [a, b, c, d, e, f]
sl1: [c, d, e]
sl2: [a, b, c, d, e]
sl3: [c, d, e, f]
dcl: [g, h, i]
t == t2
2d: [[0], [1, 2], [2, 3, 4]]

Lists in Dart are very versatile and offer many built-in methods for manipulation and querying. They are a fundamental data structure in Dart programming and are used extensively in many applications.

Now that we’ve seen lists, we’ll look at Dart’s other key built-in data structure: maps.