Range Over Built in Dart

Our program demonstrates how to use for-in loops to iterate over various built-in data structures. Let’s see how to use for-in with some of the data structures we’ve already learned.

void main() {
  // Here we use `for-in` to sum the numbers in a list. Lists work like this too.
  var nums = [2, 3, 4];
  var sum = 0;
  for (var num in nums) {
    sum += num;
  }
  print('sum: $sum');

  // `for-in` on lists provides just the value for each entry.
  // Sometimes we actually want the indexes though.
  for (var i = 0; i < nums.length; i++) {
    if (nums[i] == 3) {
      print('index: $i');
    }
  }

  // `for-in` on maps iterates over key/value pairs.
  var kvs = {'a': 'apple', 'b': 'banana'};
  kvs.forEach((k, v) => print('$k -> $v'));

  // `for-in` can also iterate over just the keys of a map.
  for (var k in kvs.keys) {
    print('key: $k');
  }

  // `for-in` on strings iterates over Unicode code points.
  // The value is the Unicode code point itself.
  var str = 'go';
  for (var c in str.runes) {
    print(String.fromCharCode(c));
  }
}

The output of the Dart program would be:

$ dart run range_over_built_in_types.dart
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
g
o

In this Dart example, we learned how to use for-in loops to iterate over lists, maps, and strings, which helps demonstrate the flexibility of iterating over various data structures in Dart.