DartProjects 2 min read

Dart CLI project: build an expense summary from a file

Read a constrained CSV export, validate rows and aggregate totals by category.

On this page

An expense summary is a small real-world project with a clear input/output contract. This version accepts a deliberately simple two-column export: category and integer amountPaise. It does not implement quoted CSV fields; use a proper CSV parser when your input permits commas, quotes or embedded newlines.

Prepare the local project

Create a console project and save this complete entry point as bin/report.dart:

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

Future<void> main(List<String> arguments) async {
  if (arguments.length != 1) {
    stderr.writeln('Usage: dart run bin/report.dart <input.csv>');
    exitCode = 64;
    return;
  }
  final totals = <String, int>{};
  var lineNumber = 0;
  try {
    final lines = File(arguments.single).openRead()
        .transform(utf8.decoder).transform(const LineSplitter());
    await for (final line in lines) {
      lineNumber++;
      if (lineNumber == 1) {
        if (line.trim() != 'category,amountPaise') {
          throw const FormatException('Expected category,amountPaise header.');
        }
        continue;
      }
      if (line.trim().isEmpty) continue;
      final cells = line.split(',');
      if (cells.length != 2) throw FormatException('Invalid row $lineNumber.');
      final category = cells[0].trim();
      final amount = int.tryParse(cells[1].trim());
      if (category.isEmpty || amount == null || amount < 0) {
        throw FormatException('Invalid expense at row $lineNumber.');
      }
      totals.update(category, (old) => old + amount, ifAbsent: () => amount);
    }
    if (lineNumber == 0) throw const FormatException('Input file is empty.');
    for (final category in totals.keys.toList()..sort()) {
      stdout.writeln('$category,${totals[category]}');
    }
  } on FileSystemException {
    stderr.writeln('Could not read the input file.');
    exitCode = 1;
  } on FormatException catch (error) {
    stderr.writeln(error.message);
    exitCode = 65;
  }
}

Use a known input

category,amountPaise
travel,12000
food,5000
travel,3000

Run dart run bin/report.dart expenses.csv. The output should contain food,5000 and travel,15000 in alphabetical order. The program streams lines instead of loading the whole file into memory, while the summary map grows with the number of distinct categories.

Verify rejection behavior

Try a missing file, an invalid header, a negative amount and a row with an extra comma. No partial successful report should be printed for malformed input. Invalid UTF-8 is also a representation error rather than a valid expense.

Refactor and extend

Extract parsing and aggregation into a pure function and test it independently of File. Keep the CLI responsible for arguments, input and exit codes. Add a JSON output mode, then decide a maximum category count and file-size policy for an untrusted batch service.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.