Back to results for “Flutter Performance Optimization”
Flutter › Dart Collections & Generics

How do commonly used higher order collection methods, such as map, where, and reduce, let you transform and filter Dart collections in a clean, declarative style?

Intermediate

Answer

Dart's collection types provide a rich set of built in higher order methods that let you transform and filter data in a clean, declarative style, including map, which applies a specific transformation function to every single item and returns a brand new collection of the transformed results, where, which returns only the specific items that satisfy a given condition, and reduce, which combines every item within a collection together into one single final value, and chaining these methods together often lets you express fairly complex data processing logic far more concisely and readably than writing the equivalent explicit manual loops yourself.
final total = orders
  .where((order) => order.isCompleted)
  .map((order) => order.total)
  .reduce((a, b) => a + b);
Real-world example An order summary screen calculates the total revenue from only the completed orders by chaining where and map together to first filter and transform the relevant orders, then reduce to sum their individual totals, all within one single concise, readable expression.

Common follow-ups: What is the difference between reduce and fold, given they both seem to combine values together?;Do these higher order methods create an entirely new collection, or do they modify the original collection directly in place?