How do you use collection-if and collection-for to declaratively build a list?
Tests Dart's declarative collection control-flow features. Answer: show collection-for to filter inside a literal, collection-if for conditional items, and combine both in one expression. Red flag: imperative loops and add() instead of literal syntax.
WHAT THIS TESTS: The interviewer wants to see that you treat Dart collection literals as expressive, declarative structures rather than mutable containers built imperatively. Specifically they are checking familiarity with collection-for and collection-if, which are control-flow elements that live inside list, set, and map literals. A senior candidate should demonstrate that these features reduce boilerplate, improve readability, and integrate cleanly with spread operators and null-aware elements.
A GOOD ANSWER COVERS: First, explain that collection-for lets you iterate an existing iterable directly inside square brackets to produce new elements, effectively replacing many map and where operations when building a literal. Second, explain that collection-if evaluates a boolean condition and includes or skips a single element without mutating a temporary list. Third, show that both constructs can be combined in one literal, optionally alongside spreads, to build complex collections declaratively. Fourth, mention type inference so the resulting literal is strongly typed without explicit generic annotations.
COMMON WRONG ANSWERS: Reaching for an imperative for-loop that declares an empty list and calls add repeatedly. Using collection-for when a simple map or where on an iterable is cleaner outside a literal. Forgetting that collection-if only adds one element, so trying to use it to conditionally spread an entire list without the spread operator. Writing verbose temporary variables instead of an inline literal expression.
LIKELY FOLLOW-UPS: How would you conditionally spread an entire sublist rather than a single element? What happens if the condition is null-aware and the boolean might be null? Can you nest collection-for elements, and what are the performance implications compared to standard iterable methods? How do these features interact with const collections?
ONE CONCRETE EXAMPLE: Suppose you have List<int> numbers = [1, 2, 3, 4, 5, 6]; and bool includeZero = true;. To build a new List<int> containing only the even numbers and optionally zero at the start, you write: final evens = [ if (includeZero) 0, for (var n in numbers) if (n.isEven) n, ];. This single literal uses collection-if to prepend zero when the flag is true, collection-for to iterate numbers, and a nested collection-if to filter evens. The analyzer infers List<int> automatically.
Read the original → dart.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.