CodeBlanks Logo Icon CodeBlanks

StreamController

Learn to create streams with StreamController.

StreamController

StreamController lets you create your own Stream manually. You send events with the add method; you close the stream with close. Listeners subscribe through controller.stream.

Example: var controller = StreamController<int>();. You send an event with controller.add(10);. You close the stream with controller.close();. You listen with await for (var n in controller.stream).

StreamController lives in the dart:async library; import 'dart:async'; is required. In real apps it is used to produce Streams from user input, timers and similar sources.

Controller flow

The flow of using a StreamController is: first create with StreamController<T>(). Send events with add. Close the stream with close. Finally listen through controller.stream with await for.

Example: var controller = StreamController<int>(); controller.add(10); controller.add(20); controller.close(); await for (var n in controller.stream) { print(n); }. Output: 10, 20.

The controller buffers events; when a listener subscribes it sends them in order. After close the stream ends and await for exits.

Practice Create a stream with StreamController

import 'dart:async' is already added. void main() async is already written. Create a StreamController<int>(). Send two events with controller.add(10) and controller.add(20). Close with controller.close(). Listen with await for (var n in controller.stream) and print with print.

Starter code

main.dart
import 'dart:async';

void main() async {
  // create a StreamController<int>, add two values, close
  // print elements with await for on the stream
}

Sample solution

main.dart
import 'dart:async';

void main() async {
  var controller = StreamController<int>();
  controller.add(10);
  controller.add(20);
  controller.close();
  await for (var n in controller.stream) {
    print(n);
  }
}

Expected output

10
20

Questions and answers

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

1 Creating a StreamController

Question
var controller = ____<int>();
Answer
var controller = StreamController<int>();

Explanation: StreamController<int>() creates a stream manually.

2 Which method is called to add an event to a StreamController?

main.dart
var c = StreamController<int>();
c.???(10);
  • emit
  • push
  • send
  • add Correct answer

Explanation: the add method sends an event to the controller.

3 Match the StreamController parts

Term Meaning
StreamController<int>() Creation
controller.add(10) Send event
controller.close() Close stream
controller.stream Stream access

All lessons in Intermediate