Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 61 ยท Projects

Project: Todo Command-Line App

Build a todo app for the terminal in Dart: an immutable model, sealed commands parsed with patterns, a pure core, JSON file storage and tests.

A todo list is small enough to finish in one sitting and big enough to need real structure. In this project you build a command-line program you could actually use: dart run bin/todo.dart add Buy milk, todo list, todo done 1. Along the way you will use almost everything from the earlier chapters: classes with const constructors, pattern matching, records, JSON, exceptions and files.

Dart and dart:io are not available on the site, so the Dart code below is read-only. The runnable TypeScript stand-ins follow the same design, with an in-memory "file" in place of the disk, so you can try every stage and watch the data survive between "program runs".

The design

The best way to keep a small program testable is to separate decisions from effects.

  • The core is pure: given a command and the current list of todos, it returns the new list and some messages. No printing, no files.
  • The shell is thin: it reads the arguments, loads the file, calls the core, saves the file and prints.
flowchart LR
    A["args"] --> P["parseCommand"]
    P --> C["Command<br/>(sealed)"]
    F["todos.json"] --> L["load"]
    L --> E["execute(command, todos)"]
    C --> E
    E --> S["save"]
    E --> O["print messages"]
    S --> F

The pure core execute sits in the middle; only load, save and print touch the outside world.

The project layout is the standard one that dart create -t console todo gives you, with a few more files:

TEXT
todo/
  pubspec.yaml
  bin/todo.dart           # the shell: main()
  lib/todo.dart           # exports the public pieces
  lib/src/todo.dart       # model
  lib/src/command.dart    # commands and parsing
  lib/src/execute.dart    # the pure core
  lib/src/store.dart      # JSON file storage
  test/todo_test.dart

Stage 1: the model

A todo has an id, a title and a done flag. Make it immutable (all fields final, const constructor) and give it a copyWith for the "change one thing" case, plus toJson and fromJson for storage.

DART
class Todo {
  const Todo({required this.id, required this.title, this.done = false});

  final int id;
  final String title;
  final bool done;

  Todo copyWith({String? title, bool? done}) =>
      Todo(id: id, title: title ?? this.title, done: done ?? this.done);

  Map<String, Object?> toJson() => {'id': id, 'title': title, 'done': done};

  factory Todo.fromJson(Map<String, Object?> json) => Todo(
        id: json['id'] as int,
        title: json['title'] as String,
        done: json['done'] as bool? ?? false,
      );

  @override
  String toString() => '[${done ? 'x' : ' '}] $id  $title';
}

Two details matter. json['done'] as bool? ?? false treats a missing field as "not done", so files written by an older version of the program still load. And toString is what the list command prints, so the format lives in one place.

The first stand-in builds the same model and shows a JSON round trip:

TypeScript Stage 1: the model and JSON (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Stage 2: commands and parsing

Every thing the user can ask for is a case of a sealed class. Because the hierarchy is sealed, a switch over a Command is checked for exhaustiveness: add a new command later and the compiler lists every switch you forgot to update.

DART
sealed class Command {}

class Add extends Command {
  Add(this.title);
  final String title;
}

class Done extends Command {
  Done(this.id);
  final int id;
}

class Remove extends Command {
  Remove(this.id);
  final int id;
}

class ListAll extends Command {}

Parsing turns List<String> into a Command with a list pattern in a switch expression. Anything that does not fit throws a FormatException, which the shell turns into a friendly message.

DART
Command parseCommand(List<String> args) => switch (args) {
      ['add', ...final words] when words.isNotEmpty => Add(words.join(' ')),
      ['done', final id] => Done(_parseId(id)),
      ['remove', final id] => Remove(_parseId(id)),
      [] || ['list'] => ListAll(),
      _ => throw FormatException('Unknown command: ${args.join(' ')}'),
    };

int _parseId(String text) {
  final id = int.tryParse(text);
  if (id == null || id <= 0) {
    throw FormatException("'$text' is not a valid id");
  }
  return id;
}

int.tryParse returns null instead of throwing, which is why we use it and then raise our own, clearer error. The when words.isNotEmpty guard makes add without a title fall through to the unknown-command arm.

TypeScript Stage 2: parsing arguments (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Stage 3: the pure core

execute takes a command and the current todos and returns a record with the new list and the messages to show. It never mutates its input; it builds new lists with spread and collection for.

DART
typedef Outcome = ({List<Todo> todos, List<String> messages});

Outcome execute(Command command, List<Todo> todos) {
  switch (command) {
    case Add(:final title):
      final nextId =
          todos.fold(0, (highest, t) => t.id > highest ? t.id : highest) + 1;
      final added = Todo(id: nextId, title: title);
      return (todos: [...todos, added], messages: ['Added: $added']);

    case Done(:final id):
      _require(todos, id);
      return (
        todos: [for (final t in todos) if (t.id == id) t.copyWith(done: true) else t],
        messages: ['Completed $id'],
      );

    case Remove(:final id):
      _require(todos, id);
      return (
        todos: [for (final t in todos) if (t.id != id) t],
        messages: ['Removed $id'],
      );

    case ListAll():
      return (
        todos: todos,
        messages: todos.isEmpty ? ['Nothing to do'] : [for (final t in todos) '$t'],
      );
  }
}

void _require(List<Todo> todos, int id) {
  if (!todos.any((t) => t.id == id)) {
    throw FormatException('No todo with id $id');
  }
}

New ids use the highest existing id plus one, not the list length. With the length, removing todo 1 from [1, 2] and adding another would produce a second todo with id 2. This is a classic bug, and a test will pin it down.

Stage 4: storage and the shell

Storage is the only code that touches the disk. It reads and writes a JSON file; jsonEncode calls each object's toJson automatically.

DART
import 'dart:convert';
import 'dart:io';

class TodoStore {
  TodoStore(this._file);
  final File _file;

  Future<List<Todo>> load() async {
    if (!await _file.exists()) return [];
    final text = await _file.readAsString();
    try {
      final data = jsonDecode(text) as List<Object?>;
      return [for (final item in data) Todo.fromJson(item as Map<String, Object?>)];
    } on TypeError {
      throw FormatException('todos.json is damaged; fix or delete it');
    }
  }

  Future<void> save(List<Todo> todos) =>
      _file.writeAsString(const JsonEncoder.withIndent('  ').convert(todos));
}

A corrupt file would otherwise surface as an unexplained cast error, so load converts it into a message the user can act on. (A malformed JSON text throws FormatException by itself.) The shell in bin/todo.dart wires everything together and sets a non-zero exit code when something goes wrong, as in files and command-line programs:

DART
import 'dart:io';
import 'package:todo/todo.dart';

Future<void> main(List<String> args) async {
  final store = TodoStore(File('todos.json'));
  try {
    final command = parseCommand(args);
    final outcome = execute(command, await store.load());
    await store.save(outcome.todos);
    outcome.messages.forEach(print);
  } on FormatException catch (e) {
    stderr.writeln('error: ${e.message}');
    exitCode = 64; // "usage error" by convention
  }
}

Now put the pieces together in a runnable stand-in. The MemoryFile plays the role of todos.json. Each call to run is like launching the program once: it builds everything from scratch and only the "file" carries data over.

TypeScript Stage 4: the whole app, eight program runs (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the output after remove 1 and add Walk dog: the new todo gets id 3, not 2, because ids are never reused.

Stage 5: tests

The pure core is easy to test, because tests need no files and no output capture. Add test as a dev dependency (dart pub add --dev test) and write the cases that matter, including the id bug from earlier.

DART
import 'package:test/test.dart';
import 'package:todo/todo.dart';

void main() {
  group('execute', () {
    test('add gives the next id', () {
      final first = execute(Add('a'), []);
      final second = execute(Add('b'), first.todos);
      expect(second.todos.map((t) => t.id), [1, 2]);
    });

    test('ids are not reused after remove', () {
      var todos = execute(Add('a'), []).todos;
      todos = execute(Add('b'), todos).todos;
      todos = execute(Remove(1), todos).todos;
      todos = execute(Add('c'), todos).todos;
      expect(todos.map((t) => t.id), [2, 3]);
    });

    test('done on a missing id fails', () {
      expect(() => execute(Done(7), []), throwsFormatException);
    });
  });

  group('parseCommand', () {
    test('joins words into a title', () {
      final command = parseCommand(['add', 'Buy', 'milk']) as Add;
      expect(command.title, 'Buy milk');
    });

    test('rejects a bad id', () {
      expect(() => parseCommand(['done', 'abc']), throwsFormatException);
    });
  });
}

Run them with dart test. The last stand-in does the same job with plain assertions, which is all package:test really automates: run named checks, catch failures, and report them.

TypeScript Stage 5: tests with plain assertions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The failing third test is deliberate: it shows how a test would have caught the length-based id bug.

Where to go next

Good extensions: a due date (use DateTime and DateTime.tryParse), priorities with an enum, a --file option, an edit command, and a clear command that removes all finished todos with removeWhere. Each one touches exactly one or two files, which is the payoff of the layout.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is execute written as a pure function that returns the new list?

    Separating decisions from effects makes the logic easy to test and the shell trivial.
  2. 2. What benefit does sealed class Command give a switch?

    A sealed hierarchy is known completely at compile time, so a switch without a default must cover every case, and adding a new command shows every switch to update.
  3. 3. Why do new todos use the highest existing id plus one, rather than todos.length + 1?

    With todos 1 and 2, removing 1 leaves length 1, so length + 1 would create a second todo with id 2.
  4. 4. What does json['done'] as bool? ?? false do for a file without a done field?

    A missing key reads as null; the cast to bool? accepts it and ?? supplies false, so older files still load.

Summary

  • Keep a pure core (execute) and a thin shell (arguments, file, printing) so the interesting logic is easy to test.
  • Model data with immutable classes, copyWith, toJson and fromJson; give missing fields sensible defaults.
  • Represent commands as a sealed class, parse arguments with list patterns, and switch exhaustively.
  • Report user mistakes with FormatException, print them to stderr and set a non-zero exitCode.
  • Write tests for the behaviours that break easily, such as id reuse, and run them with dart test.

Next: Project: Bank Account Model.