CodeBlanks Logo Icon CodeBlanks

StreamController

Create your own Stream with StreamController.

StreamController

StreamController lets you create your own Stream. You send values to the stream with sink.add and listen via the stream property.

final controller = StreamController<int>();
controller.sink.add(1);
controller.stream.listen(print);

This is the way to produce data programmatically.

sink and stream

controller.sink.add(value) sends a new value to the stream. controller.stream is the Stream used to listen to these values.

controller.sink.add('hello');
controller.stream.listen((value) {
  print(value);
});

Values from the stream are delivered to listeners.

Practice Send data with StreamController

In the VeriYoneticisi class, hold a StreamController<String>. The veriGonder method should call controller.sink.add(deger). The stream getter should return controller.stream. In main, create the manager, send 'merhaba' and call print('yönetici hazır').

Starter code

main.dart
import 'dart:async';

class VeriYoneticisi {
  // kontrolcü tanımla
  // veriGonder metodu ekle
  // stream getter ekle
}

void main() {
  final yonetici = VeriYoneticisi();
  yonetici.veriGonder('merhaba');
  print('yönetici hazır');
}

Sample solution

main.dart
import 'dart:async';

class VeriYoneticisi {
  final controller = StreamController<String>();

  void veriGonder(String deger) {
    controller.sink.add(deger);
  }

  Stream<String> get stream => controller.stream;
}

void main() {
  final yonetici = VeriYoneticisi();
  yonetici.veriGonder('merhaba');
  print('yönetici hazır');
}

Expected output

yönetici hazır

Questions and answers

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

1 What is StreamController used for?

  • You create your own Stream Correct answer
  • A widget is drawn
  • A stream listener is added
  • It produces a Future

Explanation: With StreamController you create your own Stream; you send values with sink.add and listen via stream.

2 Send a value with sink.add

Question
controller.sink.____('merhaba');
Answer
controller.sink.add('merhaba');

Explanation: controller.sink.add sends a new value to the stream; listeners receive this value.

3 StreamController parts

Term Meaning
StreamController Class creating your own Stream
sink Channel to add data to stream
stream Listenable stream
add Method to send value via sink

All lessons in Intermediate