CodeBlanks Logo Icon CodeBlanks

Stream transformer

Learn transformation with StreamTransformer.

StreamTransformer

A StreamTransformer is an abstraction that turns one stream into another. It can map, filter, group or retime each element.

The simplest transform is .map(fn): it replaces each element via fn. .where(test) filters, .take(n) takes the first n elements.

For more complex transforms, write a custom transformer with StreamTransformer.fromHandlers. This is the basis of stream pipelines.

Building a pipeline

Multiple transformers can be chained: s.where((x) => x > 0).map((x) => x * 2).take(3). Each step returns a new stream; data does not flow backwards.

At the end of the chain comes a terminal operator: forEach, listen, toList, first. This call consumes the stream.

Transformers are lazy: data does not flow until a terminal is called. This avoids unnecessary computation.

Practice Double each element with map

Make main async. Add var s = Stream.fromIterable([1, 2, 3]);. Add await s.map((x) => x * 2).forEach(print);.

Starter code

main.dart
void main() {
  // make async; build [1,2,3] stream; double via map; print via forEach
}

Sample solution

main.dart
void main() async {
  var s = Stream.fromIterable([1, 2, 3]);
  await s.map((x) => x * 2).forEach(print);
}

Expected output

2
4
6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Transform each element

Question
var t = s.____((x) => x * 2);
Answer
var t = s.map((x) => x * 2);

Explanation: map transforms each element.

2 Which is a StreamTransformer?

  • .toList()
  • .map(fn) Correct answer
  • .length
  • .toString()

Explanation: map turns one stream into another.

3 Match the operators

Term Meaning
.map(fn) Transform
.where(test) Filter
.take(n) First n elements
.forEach(fn) Consume

All lessons in Advanced