Collection-if and Collection-for in Dart

Ali
2 min readOct 10, 2023

--

Introduction

Dart, the programming language behind Flutter, offers a range of features to make your code more concise, readable, and maintainable. Two such features are collection-if and collection-for, which allows you to build more dynamic and expressive collections. In this article, we'll explore these features, their syntax, and some practical examples.

Table of Contents

Article: Understanding Collection-if and Collection-for in Dart with Examples

Introduction

Dart, the programming language behind Flutter, offers a range of features to make your code more concise, readable, and maintainable. Two such features are collection-if and collection-for, which allows you to build collections in a more dynamic and expressive manner. In this article, we'll delve into these features, explore their syntax, and look at some practical examples.

What is Collection-if?

The collection-if feature allows you to conditionally include an element in a Dart collection. This is particularly useful when you want to include or exclude items based on some condition without having to write verbose code.

var list = [
'item1',
if (condition) 'item2',
];

What is Collection-for?

The collection-for feature enables you to insert multiple elements into a collection. It is especially useful when you want to include elements from another collection or generate a series of elements dynamically.

var list = [
'item1',
for (var i in anotherList) i,
];

Examples

Using Collection-if

Let’s say you’re building a Flutter app and you want to conditionally render widgets based on the user’s role.

var userRole = 'admin';

var menuItems = <Widget>[
ListTile(title: Text('Dashboard')),
if (userRole == 'admin') ListTile(title: Text('Admin Panel')),
ListTile(title: Text('Profile')),
];

In this example, the ‘Admin Panel’ menu item will only be included in the menuItems list if userRole is 'admin'.

Using Collection-for

Suppose you have a list of numbers and you want to create a new list that includes the squares of these numbers.

var numbers = [1, 2, 3, 4, 5];
var squares = <int>[
for (var number in numbers) number * number,
];

Here, squares will be [1, 4, 9, 16, 25].

Conclusion

The collection-if and collection-for features in Dart offer a more expressive way to build collections. They make your code cleaner and more maintainable, which is crucial for large-scale applications. Whether you're a beginner or an experienced Flutter developer, understanding these features can help you write more efficient code.

--

--

Ali
Ali

Written by Ali

Ali Maher, #FlutterDev with [5 yrs] exp. Skilled in #Dart, Flutter.

No responses yet