Lesson 5 / 25

Control Flow and Collection Literals

Use conditions, loops and collection if, for and spread elements.

Familiar flow with useful extras

Dart has if/else, for, for-in (over any Iterable), while, do-while, break, continue, assert (checked in debug mode) and switch, which in Dart 3 supports patterns and does not fall through between non-empty cases. Dart adds expressive collection literals. Collection if includes an element conditionally: [ 'Home', if (isAdmin) 'Admin', 'Logout' ]. Collection for builds elements in place: [ for (final p in products) p.title ]. The spread operator ... inserts all elements of another collection, and ...? handles null. These features are used constantly in Flutter to build lists of widgets declaratively, without separate loops and temporary lists. The cascade operator .. performs several operations on the same object (paint..color = c..strokeWidth = 2), and ?.. does so only when the object is not null. Use for-in for iteration and forEach sparingly, since forEach with an async callback does not wait for each call.

Collection if, for, spread and cascades

Declarative list building, as used in Flutter widget trees.

class Product {
  const Product(this.title, this.price, {this.inStock = true});
  final String title;
  final double price;
  final bool inStock;
}

void main() {
  const products = [
    Product('Notebook', 120),
    Product('Pen', 49.5),
    Product('Ink', 199, inStock: false),
  ];
  const isAdmin = true;
  final extraLinks = <String>['Help'];

  final menu = [
    'Home',
    if (isAdmin) 'Admin',
    for (final p in products) if (p.inStock) 'Buy ${p.title}',
    ...extraLinks,
  ];
  print(menu);   // [Home, Admin, Buy Notebook, Buy Pen, Help]

  final buffer = StringBuffer()
    ..write('Order: ')
    ..write(products.length)
    ..write(' items');              // cascade: several calls on one object
  print(buffer.toString());
}

Packing a bag with a checklist

Collection if and for are a packing checklist written as the bag itself: "umbrella, if it is monsoon; one shirt for each day; plus everything from the toiletry kit". The result is the packed bag, not a set of instructions.

Quick check: What does `[ 'Home', if (isAdmin) 'Admin' ]` produce when isAdmin is false?

  • [Home, null]
  • [Home]
  • [Home, Admin]
  • A compile error
Answer

[Home] — Collection if omits the element entirely when the condition is false.