Python Collection-if, Collection-for & Spread Operators
Dart features revolutionary declarative collection operators: **Collection-if** (`[if (condition) item]`), **Collection-for** (`[for (var x in items) transform(x)]`), and the **Spread Operator** (`[...listA, ...?nullableListB]`). These operators enable constructing complex Flutter widget trees and data structures declaratively without imperatively calling `.add()`.
"Collection operators are like modular Lego building instructions: "If it's raining, add a roof block; for each window, add a shutter block; and attach this entire pre-built garage module here.""
Deep Dive: How It Works
Collection-if: Conditionally includes an element in a List, Set, or Map literal (`[if (isAdmin) "Admin Panel"]`).
Collection-for: Loops inside a literal to generate repetitive elements (`[for (var i in items) Chip(i)]`).
Spread (`...`) & Null-Aware Spread (`...?`): Flattens and unpacks elements from another collection.
Syntax Blueprint
var items = [ "Home", if (isLoggedIn) "Profile", for (var tag in tags) "#$tag", ...?optionalLinks, ];
Declarative collection literal with if, for, and null-aware spread.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using imperative `if (cond) list.add(...)` when building declarative widget trees.Why it happens: Old habit from imperative UI frameworks.
How to fix: Use inline collection-if `[if (cond) Widget()]` directly in the children list.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Assemble Dynamic Menu List
Given `bool hasDiscount = true;` and `final extras = ["Fries", "Drink"];`.
Assemble `final order = ["Burger", if (hasDiscount) "Coupon Applied", ...extras];`.
Print `Order: $order`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.