CodeBlanks Logo Icon CodeBlanks

What are streams?

Learn the stream concept and event sequences.

What is a Stream?

Stream<T> represents a sequence of events over time. A Future gives one result; a Stream delivers multiple values in order. It is used for event-driven data.

Example: var s = Stream.fromIterable([1, 2, 3]);. This is a stream that produces 1, 2 and 3 in order. To receive the values you use await for: await for (var n in s) { print(n); }.

Streams are used for user input, sensor data, network packets and other continuously flowing data. Each event is processed as it arrives; the flow continues until the stream closes.

Listening with await for

To receive the events of a Stream you use the await for loop. It resembles a for loop; but at each step it waits for the next event.

Example: await for (var n in stream) { print(n); }. Each time the Stream sends an event n takes its value and print runs. When the Stream closes the loop ends.

await for works only in async functions. So you must write void main() async. The loop waits until the Stream completes.

Practice Print Stream events

void main() async is already written. Create a stream with Stream.fromIterable([1, 2, 3]). Wait for each event with await for and print it with print.

Starter code

main.dart
void main() async {
  // create a stream with 1, 2, 3
  // print each element with await for
}

Sample solution

main.dart
void main() async {
  var s = Stream.fromIterable([1, 2, 3]);
  await for (var n in s) {
    print(n);
  }
}

Expected output

1
2
3

Questions and answers

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

1 What is the difference between Stream and Future?

  • They are exactly the same
  • Stream is faster
  • Future delivers multiple values
  • Stream delivers multiple values, Future one value Correct answer

Explanation: Stream delivers multiple values in sequence, Future gives one result.

2 Creating a Stream

Question
var s = ____.fromIterable([1, 2, 3]);
Answer
var s = Stream.fromIterable([1, 2, 3]);

Explanation: Stream.fromIterable creates a stream from a list.

3 Match the Stream parts

Term Meaning
Stream.fromIterable Stream creation
await for Listening
var n in stream Event variable
print(n) Print event

All lessons in Intermediate