Back to results for “Map”
Flutter › Dart Streams & StreamControllers

How do stream transformation methods, such as map, where, and distinct, let you process and filter the values emitted by a Stream, similar to how these same methods work on a regular Dart collection?

Intermediate

Answer

Streams support many of the exact same familiar higher order transformation methods available on regular Dart collections, including map to transform each individual emitted value, where to filter out values that do not satisfy a specific given condition, and distinct to automatically skip over any consecutive duplicate values, and chaining these transformation methods together lets you build a clean, readable processing pipeline that only actually emits the exact specific values your particular listener genuinely cares about receiving.
searchController.stream
  .where((query) => query.length > 2)
  .distinct()
  .listen((query) => performSearch(query));
Real-world example A search feature filters its stream of text input changes to only actually trigger a search once the entered query is at least three characters long, and additionally skips any exact duplicate consecutive queries, avoiding unnecessary repeated network requests.

Common follow-ups: What is the debounce transformation, and why is it especially commonly used together with a text input search stream?;Can these stream transformation methods be combined with async and await as well?