Dart Tutorial: Transforming Lists with map()

Dart Tutorial: Transforming Lists with map()

Dart provides powerful tools for working with collections, and one of the most concise and expressive methods is map(). This function allows you to apply a transformation to each element of a list (or any iterable), returning a new lazy iterable with the results.

What is map() in Dart?

The map() function creates a new iterable by applying a function to each element of the original iterable. It does not modify the original list — instead, it returns a lazy iterable, which means it only computes values when accessed.

Use Case Example: Converting Numbers to Strings with Prefix

Let’s look at a simple example: you have a list of numbers, and you want to convert each number to a string with a prefix like "ID_".


void main() {
List<int> numbers = [1, 2, 3, 4, 5];

// Transform each number into a string with prefix using map()
List<String> transformed = numbers.map((number) => 'ID_$number').toList();

print(transformed); // Output: [ID_1, ID_2, ID_3, ID_4, ID_5]
}


Tips

  • map() can be chained with other methods like where() and reduce() for more complex operations.

  • Always call .toList() if you need the result as a regular list, especially in Flutter UI builds.

When to Use map()

Use map() when:

  • You want to transform the elements of a collection.

  • You don’t want to mutate the original list.

  • You prefer expressive, functional-style Dart code.

Preview of Output


Original List: [1, 2, 3, 4, 5]
Mapped List: [ID_1, ID_2, ID_3, ID_4, ID_5]

This small function can significantly clean up your code and is commonly used in real-world Dart and Flutter applications.

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *