Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Collection if and for


Share

Dart Collection if and for

A literal is a value you write directly in the code, like [1, 2, 3] or {'a': 1}.

Dart lets you write if and for inside list, set and map literals.

This is called collection if and collection for.

It lets you build a collection in one step, without calling add() many times.


Collection if

Put if before an item to add that item only when the condition is true.

Note that there are no curly brackets around the item:

Example

void main() {
  var isLoggedIn = true;
  var menu = ['Home', 'Tutorials', if (isLoggedIn) 'My Profile'];
  print(menu);
}
Try it Yourself »

Result:

[Home, Tutorials, My Profile]

If the condition is false, the item is left out:

Example

void main() {
  var isLoggedIn = false;
  var menu = ['Home', 'Tutorials', if (isLoggedIn) 'My Profile'];
  print(menu);
}
Try it Yourself »

Result:

[Home, Tutorials]

You can also add an else part, to pick one of two items:

Example

void main() {
  var isLoggedIn = false;
  var menu = ['Home', 'Tutorials', if (isLoggedIn) 'Log out' else 'Log in'];
  print(menu);
}
Try it Yourself »

Result:

[Home, Tutorials, Log in]


Collection for

Put a for loop inside a literal to add one item for each run of the loop:

Example

void main() {
  var numbers = [1, 2, 3, 4];
  var doubled = [for (var n in numbers) n * 2];
  print(doubled);
}
Try it Yourself »

Result:

[2, 4, 6, 8]

You can mix normal items and a for in the same literal:

Example

void main() {
  var fruits = ['apple', 'banana'];
  var shopping = ['milk', for (var f in fruits) f.toUpperCase(), 'bread'];
  print(shopping);
}
Try it Yourself »

Result:

[milk, APPLE, BANANA, bread]

A classic counting loop works too:

Example

void main() {
  var squares = [for (var i = 1; i <= 5; i++) i * i];
  print(squares);
}
Try it Yourself »

Result:

[1, 4, 9, 16, 25]

Combine for and if

You can put an if inside a for, to keep only some items:

Example

void main() {
  var scores = [45, 82, 67, 91, 38];
  var passed = [for (var s in scores) if (s >= 50) s];
  print(passed);
}
Try it Yourself »

Result:

[82, 67, 91]

Sets and Maps

Collection if and for also work in set literals:

Example

void main() {
  var words = ['dart', 'java', 'dart', 'kotlin', 'java'];
  var firstLetters = {for (var w in words) w[0]};
  print(firstLetters);
}
Try it Yourself »

Result:

{d, j, k}

In a map literal, each item is a key: value pair:

Example

void main() {
  var names = ['Tom', 'Anna', 'Linus'];
  var nameLengths = {for (var name in names) name: name.length};
  print(nameLengths);

  var showEmail = true;
  var user = {
    'name': 'Anna',
    if (showEmail) 'email': 'anna@example.com',
  };
  print(user);
}
Try it Yourself »

Result:

{Tom: 3, Anna: 4, Linus: 5}
{name: Anna, email: anna@example.com}


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.