CodeBlanks Logo Icon CodeBlanks

What is a Stream?

Learn that a Stream emits multiple values over time.

What is Stream?

Stream is a data flow that can produce multiple values over time. While a Future produces a single value, a Stream keeps emitting values.

Stream<int> numbers() async* {
  yield 1;
  yield 2;
  yield 3;
}

You produce a Stream with async* and yield.

async* and yield

To produce a Stream, you write a function marked with async*. You publish each value with yield.

Stream<int> numbers() async* {
  yield 1;
  yield 2;
}

Each yield adds a value to the stream.

Practice Produce a number stream with async*

Write an async* function named sayiAkisi returning Stream<int>. Produce 0, 1 and 2 with yield. In main, listen to the stream and print each value with print('değer: $deger').

Starter code

main.dart
import 'package:flutter/material.dart';

// sayiAkisi fonksiyonunu ekle

void main() {
  final stream = sayiAkisi();
  stream.listen((deger) {
    print('değer: $deger');
  });
}

Sample solution

main.dart
import 'package:flutter/material.dart';

Stream<int> sayiAkisi() async* {
  yield 0;
  yield 1;
  yield 2;
}

void main() {
  final stream = sayiAkisi();
  stream.listen((deger) {
    print('değer: $deger');
  });
}

Expected output

değer: 0
değer: 1
değer: 2

Questions and answers

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

1 What is the main difference between Stream and Future?

  • Stream only throws errors
  • Future produces one value, Stream many Correct answer
  • Stream produces one value, Future many
  • Neither produces any value

Explanation: Future produces a single value and completes; Stream keeps producing multiple values over time.

2 Produce a value with yield

Question
Stream<int> sayilar() async* {
  ____ 1;
  yield 2;
}
Answer
Stream<int> sayilar() async* {
  yield 1;
  yield 2;
}

Explanation: Inside an async* function, yield adds a value to the stream; each yield publishes one value.

3 Stream parts

Term Meaning
Stream Flow producing multiple values over time
async* Marker for Stream-producing function
yield Adding a value to the stream
Future Async result producing a single value

All lessons in Intermediate