Using Streams with Transformations

This example shows how to transform data in a stream.

import 'dart:async';

void main() {
  var controller = StreamController<int>();

  // Listen to the stream
  controller.stream
      .map((number) => number * number) // Transform numbers to their squares
      .listen((squared) {
    print('Squared: $squared');
  });

  // Add data to the stream
  for (var i = 1; i <= 5; i++) {
    controller.add(i);
  }

  controller.close();
}

Comments

Leave a Reply

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