What are Collection If and For?
Dart allows you to use if and for inside collection literals (lists, sets, and maps). This feature, introduced in Dart 2.3, lets you build collections dynamically in a declarative way. It's especially useful for UI code in Flutter, where you often need to conditionally include widgets or generate multiple widgets from a list of data.
Collection if
The if element lets you conditionally include an element or a spread inside a collection. The condition must be a boolean expression. If the condition is true, the element or spread is included; otherwise, it's omitted.
You can also use if-else inside collections. The else clause provides an alternative element when the condition is false.
Collection for
The for element allows you to iterate over an iterable and include elements generated from each iteration. It's like a loop inside the collection literal.
You can also use the index if you need it, by iterating over a range or using asMap().
Combining if and for with Spread
You can mix if, for, and the spread operator (...) to build complex collections concisely.
Using if and for in Sets
Sets also support if and for. The syntax is identical to lists.
Using if and for in Maps
Maps also support if and for, but you need to provide key‑value pairs. For for, you can generate entries.
Nested Collection for
You can nest for loops inside each other to create more complex structures, like a multiplication table.
Real‑World Example: Flutter Widgets
This feature is extremely common in Flutter for building UI conditionally or from lists. For instance, a Column with children generated from a list of items:
Key Takeaways
- Collection
ifconditionally includes an element or spread.
- Collection
- Collection
foriterates and includes generated elements.
- Collection
- Both work in list, set, and map literals.
- Combine with spread
...for flexible inclusion of multiple elements.
- Combine with spread
- Use
if-elseto provide alternative elements.
- Use
- Nested
forloops are allowed for multi‑level generation.
- Nested
- This feature makes collection building declarative and readable, especially in Flutter UI code.