Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code snippet for "How to use Streams in Dart (Part 2)" series
import 'dart:async';
void main() {
var controller = StreamController<num>();
// Create StreamTransformer with transformer closure
var streamTransformer = StreamTransformer<num, num>.fromHandlers(
handleData: (num data, EventSink sink) {
sink.add(data * 2);
},
handleError: (error, stacktrace, sink) {
sink.addError('Something went wrong: $error');
},
handleDone: (sink) {
sink.close();
},
);
// Call the `transform` method on the controller's stream
// while passing in the stream transformer
var controllerStream = controller.stream.transform(streamTransformer);
// Just print out transformations to the console
controllerStream.listen(print);
// Add data to stream to see transformations in effect
controller.sink.add(1); // 2
controller.sink.add(2); // 4
controller.sink.add(3); // 6
controller.sink.add(4); // 8
controller.sink.add(5); // 10
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.