TExcelTAD
Home › Dart › Dart Mini Project: Bookstore CLI

Dart Mini Project: Bookstore CLI

Time to put everything together. In this project you'll build the core of PageTurner, a small command-line bookstore. It parses a JSON catalog, searches and filters books, manages a shopping cart with discounts, processes commands, and simulates an async checkout. Each step adds one layer and is runnable on its own; the final step combines them.

Features you'll use: classes and enums, records and patterns, sealed classes, extension methods, collections, exceptions, JSON and async/await.

text
pageturner/
├── bin/pageturner.dart        ← main(): reads commands from stdin
├── lib/
│   ├── models.dart            ← Book, Genre
│   ├── catalog.dart           ← parsing + search
│   ├── cart.dart              ← Cart, discounts
│   └── commands.dart          ← sealed Command + parser
└── test/cart_test.dart

On a real machine you'd split the code across these files and import 'package:pageturner/models.dart';. In the playground, each step is one file.

Step 1 — Models from JSON

An enhanced enum for genres and an immutable Book with a fromJson factory. Money is stored as integer cents to avoid floating-point surprises.

dart · try it yourself
import 'dart:convert';

enum Genre {
  fiction('Fiction'),
  science('Science'),
  history('History');

  const Genre(this.label);
  final String label;

  static Genre parse(String s) => values.asNameMap()[s] ?? fiction;
}

class Book {
  final String isbn;
  final String title;
  final String author;
  final Genre genre;
  final int priceCents;

  const Book(this.isbn, this.title, this.author, this.genre, this.priceCents);

  factory Book.fromJson(Map<String, dynamic> j) => switch (j) {
        {'isbn': String isbn, 'title': String title, 'author': String author,
         'genre': String genre, 'price': num price} =>
          Book(isbn, title, author, Genre.parse(genre), (price * 100).round()),
        _ => throw FormatException('bad book record: $j'),
      };

  @override
  String toString() => '$title by $author';
}

const catalogJson = '''
[
  {"isbn": "111", "title": "Dune", "author": "Frank Herbert", "genre": "fiction", "price": 9.99},
  {"isbn": "222", "title": "Cosmos", "author": "Carl Sagan", "genre": "science", "price": 14.5},
  {"isbn": "333", "title": "SPQR", "author": "Mary Beard", "genre": "history", "price": 18},
  {"isbn": "444", "title": "Foundation", "author": "Isaac Asimov", "genre": "fiction", "price": 8.25}
]
''';

void main() {
  final books = (jsonDecode(catalogJson) as List)
      .map((e) => Book.fromJson(e as Map<String, dynamic>))
      .toList();
  for (final b in books) {
    print('${b.isbn}  ${b.genre.label.padRight(8)} ${b.priceCents.toString().padLeft(5)}c  $b');
  }
}
111  Fiction    999c  Dune by Frank Herbert
222  Science   1450c  Cosmos by Carl Sagan
333  History   1800c  SPQR by Mary Beard
444  Fiction    825c  Foundation by Isaac Asimov

The map pattern in fromJson validates the shape and types in one go.

Step 2 — Formatting money and searching

An extension makes cents print nicely, and a Catalog class offers search with optional named filters.

dart · try it yourself
extension Money on int {
  String get usd => '\${(this ~/ 100)}.${(this % 100).toString().padLeft(2, '0')}';
}

enum Genre { fiction, science, history }

class Book {
  final String isbn, title, author;
  final Genre genre;
  final int priceCents;
  const Book(this.isbn, this.title, this.author, this.genre, this.priceCents);
}

class Catalog {
  final Map<String, Book> _byIsbn;
  Catalog(Iterable<Book> books) : _byIsbn = {for (final b in books) b.isbn: b};

  Book? find(String isbn) => _byIsbn[isbn];

  List<Book> search({String? text, Genre? genre, int? maxPriceCents}) {
    final query = text?.toLowerCase();
    return [
      for (final b in _byIsbn.values)
        if ((query == null ||
                b.title.toLowerCase().contains(query) ||
                b.author.toLowerCase().contains(query)) &&
            (genre == null || b.genre == genre) &&
            (maxPriceCents == null || b.priceCents <= maxPriceCents))
          b,
    ]..sort((a, b) => a.priceCents.compareTo(b.priceCents));
  }
}

void main() {
  final catalog = Catalog(const [
    Book('111', 'Dune', 'Frank Herbert', Genre.fiction, 999),
    Book('222', 'Cosmos', 'Carl Sagan', Genre.science, 1450),
    Book('333', 'SPQR', 'Mary Beard', Genre.history, 1800),
    Book('444', 'Foundation', 'Isaac Asimov', Genre.fiction, 825),
  ]);

  print(catalog.search(genre: Genre.fiction).map((b) => '${b.title} ${b.priceCents.usd}').toList());
  print(catalog.search(text: 'sagan').map((b) => b.title).toList());
  print(catalog.search(maxPriceCents: 1500).length);
  print(catalog.find('999')?.title ?? 'not found');
  print(5.usd);
}
[Foundation $8.25, Dune $9.99]
[Cosmos]
3
not found
$0.05

Step 3 — The cart and discounts

Discounts are a sealed family, so applying one is an exhaustive switch. The cart guards its state with private fields and throws meaningful exceptions.

dart · try it yourself
extension Money on int {
  String get usd => '\${(this ~/ 100)}.${(this % 100).toString().padLeft(2, '0')}';
}

class Book {
  final String isbn, title;
  final int priceCents;
  const Book(this.isbn, this.title, this.priceCents);
}

sealed class Discount {
  const Discount();
}

class PercentOff extends Discount {
  final int percent;
  const PercentOff(this.percent);
}

class AmountOff extends Discount {
  final int cents;
  const AmountOff(this.cents);
}

class BuyXGetCheapestFree extends Discount {
  final int x;
  const BuyXGetCheapestFree(this.x);
}

class CartException implements Exception {
  final String message;
  CartException(this.message);
  @override
  String toString() => 'CartException: $message';
}

class Cart {
  final _lines = <String, (Book, int)>{}; // isbn -> (book, quantity)
  Discount? discount;

  void add(Book book, [int qty = 1]) {
    if (qty <= 0) throw CartException('quantity must be positive');
    final current = _lines[book.isbn]?.$2 ?? 0;
    _lines[book.isbn] = (book, current + qty);
  }

  void remove(String isbn) {
    if (_lines.remove(isbn) == null) throw CartException('$isbn is not in the cart');
  }

  int get itemCount => _lines.values.fold(0, (sum, line) => sum + line.$2);
  int get subtotal => _lines.values.fold(0, (sum, line) => sum + line.$1.priceCents * line.$2);

  int get savings {
    final units = [
      for (final (book, qty) in _lines.values)
        for (var i = 0; i < qty; i++) book.priceCents,
    ]..sort();
    return switch (discount) {
      null => 0,
      PercentOff(:final percent) => subtotal * percent ~/ 100,
      AmountOff(:final cents) => cents > subtotal ? subtotal : cents,
      BuyXGetCheapestFree(:final x) => units.length >= x ? units.first : 0,
    };
  }

  int get total => subtotal - savings;

  String receipt() => [
        for (final (book, qty) in _lines.values)
          '${book.title.padRight(12)} x$qty ${(book.priceCents * qty).usd.padLeft(8)}',
        '${'Subtotal'.padRight(15)} ${subtotal.usd.padLeft(8)}',
        if (savings > 0) '${'Discount'.padRight(15)} ${'-${savings.usd}'.padLeft(8)}',
        '${'TOTAL'.padRight(15)} ${total.usd.padLeft(8)}',
      ].join('\n');
}

void main() {
  const dune = Book('111', 'Dune', 999);
  const cosmos = Book('222', 'Cosmos', 1450);
  const foundation = Book('444', 'Foundation', 825);

  final cart = Cart()
    ..add(dune, 2)
    ..add(cosmos)
    ..add(foundation);

  for (final d in [null, PercentOff(10), AmountOff(500), BuyXGetCheapestFree(3)]) {
    cart.discount = d;
    print('${d.runtimeType}: ${cart.total.usd}');
  }

  cart.discount = const BuyXGetCheapestFree(3);
  print(cart.receipt());

  try {
    cart.remove('999');
  } on CartException catch (e) {
    print(e);
  }
}
Null: $42.73
PercentOff: $38.46
AmountOff: $37.73
BuyXGetCheapestFree: $34.48
Dune         x2   $19.98
Cosmos       x1   $14.50
Foundation   x1    $8.25
Subtotal          $42.73
Discount          -$8.25
TOTAL             $34.48
CartException: 999 is not in the cart

Step 4 — Parsing commands

Users type commands like add 111 2. A sealed Command hierarchy plus list patterns turn raw text into typed commands — and invalid input becomes an Invalid command instead of a crash.

dart · try it yourself
sealed class Command {}

class Search extends Command {
  final String text;
  Search(this.text);
}

class Add extends Command {
  final String isbn;
  final int qty;
  Add(this.isbn, this.qty);
}

class Remove extends Command {
  final String isbn;
  Remove(this.isbn);
}

class Checkout extends Command {}

class Invalid extends Command {
  final String reason;
  Invalid(this.reason);
}

Command parse(String line) {
  final words = line.trim().split(RegExp(r'\s+'));
  return switch (words) {
    ['search', ...final rest] when rest.isNotEmpty => Search(rest.join(' ')),
    ['add', final isbn] => Add(isbn, 1),
    ['add', final isbn, final qty] => switch (int.tryParse(qty)) {
        final n? when n > 0 => Add(isbn, n),
        _ => Invalid('quantity must be a positive number'),
      },
    ['remove', final isbn] => Remove(isbn),
    ['checkout'] => Checkout(),
    [final cmd, ...] => Invalid('unknown command "$cmd"'),
    [] => Invalid('empty input'),
  };
}

String describe(Command c) => switch (c) {
      Search(:final text) => 'search for "$text"',
      Add(:final isbn, :final qty) => 'add $qty of $isbn',
      Remove(:final isbn) => 'remove $isbn',
      Checkout() => 'checkout',
      Invalid(:final reason) => 'error: $reason',
    };

void main() {
  for (final line in ['search carl sagan', 'add 111', 'add 222 3', 'add 333 zero',
                      'remove 111', 'checkout', 'dance', 'search']) {
    print('${line.padRight(18)} -> ${describe(parse(line))}');
  }
}
search carl sagan  -> search for "carl sagan"
add 111            -> add 1 of 111
add 222 3          -> add 3 of 222
add 333 zero       -> error: quantity must be a positive number
remove 111         -> remove 111
checkout           -> checkout
dance              -> error: unknown command "dance"
search             -> error: unknown command "search"

Note that ''.split(...) returns [''], never an empty list — so the [] case is there only for exhaustiveness.

Step 5 — The complete app with async checkout

Finally, a Store ties it all together. It processes a scripted session (on a real machine, lines would come from stdin), and checkout calls a simulated payment service with a timeout.

dart · try it yourself
import 'dart:async';

extension Money on int {
  String get usd => '\${(this ~/ 100)}.${(this % 100).toString().padLeft(2, '0')}';
}

class Book {
  final String isbn, title, author;
  final int priceCents;
  const Book(this.isbn, this.title, this.author, this.priceCents);
}

sealed class Command {}
class Search extends Command { final String text; Search(this.text); }
class Add extends Command { final String isbn; final int qty; Add(this.isbn, this.qty); }
class Checkout extends Command {}
class Invalid extends Command { final String reason; Invalid(this.reason); }

Command parse(String line) => switch (line.trim().split(RegExp(r'\s+'))) {
      ['search', ...final rest] when rest.isNotEmpty => Search(rest.join(' ')),
      ['add', final isbn] => Add(isbn, 1),
      ['add', final isbn, final q] when (int.tryParse(q) ?? 0) > 0 => Add(isbn, int.parse(q)),
      ['checkout'] => Checkout(),
      _ => Invalid('cannot understand "$line"'),
    };

class PaymentDeclined implements Exception {
  final String reason;
  PaymentDeclined(this.reason);
}

/// Simulated payment provider: slow, and declines large amounts.
Future<String> charge(int cents) async {
  await Future.delayed(Duration(milliseconds: 20));
  if (cents > 5000) throw PaymentDeclined('limit exceeded');
  return 'PAY-${cents.toRadixString(16).toUpperCase()}';
}

class Store {
  final Map<String, Book> catalog;
  final Map<String, int> cart = {};
  Store(List<Book> books) : catalog = {for (final b in books) b.isbn: b};

  int get total => cart.entries.fold(0, (s, e) => s + catalog[e.key]!.priceCents * e.value);

  Future<String> handle(Command cmd) async {
    switch (cmd) {
      case Search(:final text):
        final hits = catalog.values
            .where((b) => '${b.title} ${b.author}'.toLowerCase().contains(text.toLowerCase()))
            .map((b) => '${b.isbn}:${b.title}');
        return hits.isEmpty ? 'no results' : hits.join(', ');
      case Add(:final isbn, :final qty):
        final book = catalog[isbn];
        if (book == null) return 'unknown ISBN $isbn';
        cart.update(isbn, (q) => q + qty, ifAbsent: () => qty);
        return 'added $qty x ${book.title} (cart ${total.usd})';
      case Checkout():
        if (cart.isEmpty) return 'cart is empty';
        try {
          final ref = await charge(total).timeout(Duration(milliseconds: 500));
          final paid = total;
          cart.clear();
          return 'paid ${paid.usd}, ref $ref';
        } on PaymentDeclined catch (e) {
          return 'payment declined: ${e.reason}';
        } on TimeoutException {
          return 'payment timed out, try again';
        }
      case Invalid(:final reason):
        return reason;
    }
  }
}

Future<void> main() async {
  final store = Store(const [
    Book('111', 'Dune', 'Frank Herbert', 999),
    Book('222', 'Cosmos', 'Carl Sagan', 1450),
    Book('333', 'SPQR', 'Mary Beard', 1800),
  ]);

  const session = [
    'search dune',
    'add 111',
    'add 333 3',
    'checkout',
    'hello?',
    'search beard',
    'checkout',
  ];

  for (final line in session) {
    print('> $line');
    print('  ${await store.handle(parse(line))}');
  }

  // Start over with a smaller order
  store.cart.clear();
  for (final line in ['add 222 2', 'checkout', 'checkout']) {
    print('> $line');
    print('  ${await store.handle(parse(line))}');
  }
}
> search dune
  111:Dune
> add 111
  added 1 x Dune (cart $9.99)
> add 333 3
  added 3 x SPQR (cart $63.99)
> checkout
  payment declined: limit exceeded
> hello?
  cannot understand "hello?"
> search beard
  333:SPQR
> checkout
  payment declined: limit exceeded
> add 222 2
  added 2 x Cosmos (cart $29.00)
> checkout
  paid $29.00, ref PAY-B54
> checkout
  cart is empty

Ideas to extend it

  • Read commands from the terminal: import 'dart:io'; then stdin.readLineSync() in a loop (needs a real machine).
  • Add a discount <code> command that maps codes to the sealed Discount types from step 3.
  • Persist the cart as JSON with jsonEncode and File('cart.json').writeAsString(...).
  • Write package:test tests for parse and Cart — each switch case deserves one.
  • Move the catalog loading into an isolate with Isolate.run once it holds thousands of books.

Test yourself

Why does the project store prices as integer cents?

  1. Integers are smaller
  2. To avoid floating-point rounding errors with money
  3. JSON can't hold doubles
  4. Dart doubles are 32-bit

What makes adding a new Command subclass safe in this design?

  1. Every Command has a default handler
  2. Command is sealed, so every switch without that case becomes a compile error
  3. The parser ignores new commands
  4. Commands are enums

What does charge(total).timeout(Duration(milliseconds: 500)) add?

  1. Retries the payment
  2. Fails with a TimeoutException if payment takes longer than 500 ms
  3. Delays the payment by 500 ms
  4. Runs the payment in an isolate