flutter
/

Dart Collection If and For – Conditional and Iterative Collection Elements

Last Sync: Today

On this page

9
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Collection If and For – Conditional and Iterative Collection Elements

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.

DARTRead-only
1
void main() {
  bool includeThree = true;
  var numbers = [1, 2, if (includeThree) 3, 4];
  print(numbers); // [1, 2, 3, 4]
  
  includeThree = false;
  numbers = [1, 2, if (includeThree) 3, 4];
  print(numbers); // [1, 2, 4]
}

You can also use if-else inside collections. The else clause provides an alternative element when the condition is false.

DARTRead-only
1
void main() {
  bool isLoggedIn = true;
  var menu = [
    'Home',
    if (isLoggedIn) 'Profile' else 'Login',
    'Settings',
  ];
  print(menu); // [Home, Profile, Settings]
  
  isLoggedIn = false;
  menu = [
    'Home',
    if (isLoggedIn) 'Profile' else 'Login',
    'Settings',
  ];
  print(menu); // [Home, Login, Settings]
}

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.

DARTRead-only
1
void main() {
  var baseNumbers = [1, 2, 3];
  var doubled = [for (var n in baseNumbers) n * 2];
  print(doubled); // [2, 4, 6]
}

You can also use the index if you need it, by iterating over a range or using asMap().

DARTRead-only
1
void main() {
  var fruits = ['apple', 'banana', 'cherry'];
  var withIndex = [
    for (int i = 0; i < fruits.length; i++)
      '${i + 1}: ${fruits[i]}'
  ];
  print(withIndex); // [1: apple, 2: banana, 3: cherry]
}

Combining if and for with Spread

You can mix if, for, and the spread operator (...) to build complex collections concisely.

DARTRead-only
1
void main() {
  bool showExtra = true;
  var extraItems = [4, 5];
  var numbers = [
    1,
    2,
    if (showExtra) ...extraItems,
    for (var i = 6; i <= 8; i++) i,
    9,
  ];
  print(numbers); // [1, 2, 4, 5, 6, 7, 8, 9]
}

Using if and for in Sets

Sets also support if and for. The syntax is identical to lists.

DARTRead-only
1
void main() {
  bool includeD = true;
  var letters = {
    'a',
    'b',
    'c',
    if (includeD) 'd',
    for (var i = 0; i < 3; i++) 'e$i',
  };
  print(letters); // {a, b, c, d, e0, e1, e2}
}

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.

DARTRead-only
1
void main() {
  bool includeAge = true;
  var person = {
    'name': 'Alice',
    if (includeAge) 'age': 30,
    for (var i = 1; i <= 2; i++) 'key$i': 'value$i',
  };
  print(person); // {name: Alice, age: 30, key1: value1, key2: value2}
}

Nested Collection for

You can nest for loops inside each other to create more complex structures, like a multiplication table.

DARTRead-only
1
void main() {
  var rows = [1, 2, 3];
  var cols = [1, 2, 3];
  var table = [
    for (var r in rows)
      [for (var c in cols) r * c]
  ];
  print(table); // [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
}

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:

DARTRead-only
1
// Flutter example (conceptual)
Column(
  children: [
    Text('Header'),
    if (items.isNotEmpty) ...[
      for (var item in items)
        ListTile(title: Text(item)),
    ] else
      Text('No items'),
    Text('Footer'),
  ],
)

Key Takeaways

    • Collection if conditionally includes an element or spread.
    • Collection for iterates and includes generated elements.
    • Both work in list, set, and map literals.
    • Combine with spread ... for flexible inclusion of multiple elements.
    • Use if-else to provide alternative elements.
    • Nested for loops are allowed for multi‑level generation.
    • This feature makes collection building declarative and readable, especially in Flutter UI code.

Try it yourself

void main() {
  bool isWeekend = true;
  var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
  
  var schedule = [
    'Wake up',
    if (isWeekend) 'Relax' else 'Go to work',
    for (var day in days) 'Meeting on $day',
    'Sleep',
  ];
  
  for (var item in schedule) {
    print(item);
  }
}

Test Your Knowledge

Q1
of 4

What is the output of this code? void main() { bool flag = true; var list = [1, if (flag) 2, 3]; print(list); }

A
[1, 3]
B
[1, 2, 3]
C
[1, 2, 3] with a warning
D
Error
Q2
of 4

What does the following code produce? void main() { var list = [for (int i = 1; i <= 3; i++) i * i]; print(list); }

A
[1, 4, 9]
B
[1, 2, 3]
C
[1, 4, 9, 16]
D
Error
Q3
of 4

Which of the following correctly uses `if-else` inside a list?

A
[if (x > 0) then 'positive' else 'negative']
B
[if (x > 0) 'positive' else 'negative']
C
[x > 0 ? 'positive' : 'negative']
D
Both B and C are valid, but C is ternary, not collection if-else
Q4
of 4

How would you include all elements of a nullable list `extra?` inside another list without causing an error if `extra` is null?

A
[...extra]
B
[...?extra]
C
[if (extra != null) ...extra]
D
Both B and C work, but B is the null‑aware spread

Frequently Asked Questions

Can I use `else` with collection `if`?

Yes, Dart supports if-else inside collections. For example: [if (condition) 'yes' else 'no'].

What's the difference between collection `for` and the `forEach()` method?

Collection for is used to generate elements inside a collection literal. The forEach() method performs an action on each element of an existing collection but does not create a new collection.

Can I nest collection `for` loops?

Yes, you can nest for loops to create multi‑dimensional structures, like a list of lists representing a multiplication table.

Is collection `if/for` available in all collection types?

Yes, it works in List, Set, and Map literals. For maps, the for must produce key‑value pairs (e.g., 'key$i': value).

Does collection `if/for` affect performance?

No, it's a compile‑time feature that expands into the equivalent code. It has no runtime overhead compared to writing the same logic manually.

Previous

dart spread operator

Next

dart classes

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.