CodeBlanks Logo Icon CodeBlanks

Putting it together

Combine all layers into a working app.

Putting it together

In the final step you combine everything and emit tasks through a Stream. A Stream is an asynchronous data flow.

You turn a list into a Stream with Stream<Task>.fromIterable(tasks). You listen with await for (var t in stream).

For this main must now be async: void main() async { ... }. This is required to use await.

Async main and Stream

Typical usage: void main() async { var stream = Stream<Task>.fromIterable(tasks); await for (var t in stream) { print(t.title); } }.

Stream.fromIterable emits each list element in order. await for waits for each value and processes it; the loop runs until the Stream ends.

This pattern combines file + collections + Stream; it gives the skeleton of a real console app.

Practice Print tasks with a Stream

Make main async. Define var tasks = <Task>[Task('Code write'), Task('Test write')];. Create var file = File('tasks.txt'); and write with file.writeAsStringSync(tasks.map((t) => t.title).join('\n'));. Build a Stream with var stream = Stream<Task>.fromIterable(tasks); and print each title with await for (var t in stream) { print(t.title); }.

Starter code

main.dart
import 'dart:io';

abstract class Trackable {
  bool get isDone;
}

class Task implements Trackable {
  final String title;
  bool done;
  Task(this.title, {this.done = false});

  @override
  bool get isDone => done;
}

void main() {
  // create a tasks list, write to a file, print with a Stream
}

Sample solution

main.dart
import 'dart:io';

abstract class Trackable {
  bool get isDone;
}

class Task implements Trackable {
  final String title;
  bool done;
  Task(this.title, {this.done = false});

  @override
  bool get isDone => done;
}

void main() async {
  var tasks = <Task>[Task('Code write'), Task('Test write')];
  var file = File('tasks.txt');
  file.writeAsStringSync(tasks.map((t) => t.title).join('\n'));
  var stream = Stream<Task>.fromIterable(tasks);
  await for (var t in stream) {
    print(t.title);
  }
}

Expected output

Code write
Test write

Questions and answers

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

1 Listening to a Stream

Question
await for (var t in ____) { print(t.title); }
Answer
await for (var t in stream) { print(t.title); }

Explanation: await for listens to stream.

2 Stream parts

Term Meaning
Stream.fromIterable List to Stream
await for Listen loop
async Async main
yield Emit a value

3 How is a Stream listened to?

  • for (var t in stream)
  • while (stream)
  • await for (var t in stream) Correct answer
  • stream.next()

Explanation: await for is the way to listen to a Stream.

All lessons in Intermediate