Skip to content

Of course. In this chapter, we'll explore a modern Dart feature that not only makes your code cleaner but can also make it more efficient: Collection for and if.


Dart Core Optimization Series ​

Chapter 4: Collection for and if — For Cleaner, Faster Code ​

The Scenario 📝 ​

  • The Goal: In a Dart application, we need to create a new List by filtering and transforming items from an existing List.
  • The Task: Create a list of Text widgets for all users who are currently active (isActive).

The Traditional Method (using .where().map()) ​

This approach is very common, especially for developers familiar with functional programming styles.

dart
// allUsers is a List<User>
final activeUserWidgets = allUsers
  .where((user) => user.isActive) // Filter
  .map((user) => Text(user.name)) // Transform
  .toList(); // Create the new List

Analyzing the (Potential) Bottleneck 🧐 ​

  1. Intermediate Iterables: Although Dart performs these operations lazily, each call to .where() and .map() creates a new Iterable object that wraps the previous one.
  2. Overhead: Creating these Iterable objects and their anonymous functions isn't free. It adds a small cost in memory and processing time, which can become noticeable in "hot" loops or with very large datasets.

The Solution: Using Collection for and if ✅ ​

  • The Logic: Dart allows you to write loops and conditions directly inside the syntax for creating a collection ([] for a List, {} for a Set or Map).

  • The Optimized Code:

dart
final activeUserWidgets = [
  // A for loop inside the List literal
  for (final user in allUsers)
  // An if condition inside the List literal
  if (user.isActive)
    Text(user.name) // The element is added if the condition is true
];

Analyzing the Results ✨ ​

  1. Easier to Read: For many developers, this syntax is more natural. It reads like plain English: "Create a list, and for each user in all users, if that user is active, add a Text widget."
  2. More Efficient: This method is often faster and uses less memory. It translates directly into a single, efficient for loop that adds items directly to the final List without creating any intermediate Iterable objects.

Conclusion:

  • Golden Rule: When building a new collection from an existing one by filtering and transforming, always prefer using collection for and if.
  • This is a modern Dart idiom that helps you write code that is clean, easy to understand, and highly performant.