Thuta Learning
Dart
ProjectsProgrammingBeginner

Mini Project

DartLesson 2635 min

What you'll walk away with

  • Design the data first with a small immutable class before writing any logic
  • Parse untrusted text at the program's edge and return null for unusable lines
  • Return several related results at once with a named record
  • Decide and document how empty lists and ties behave
  • Keep logic in small pure functions and let main() only wire things together and print

Explain it simply

Explain it simply

A mini project is the first time you stop practising one feature at a time and make several of them cooperate. Here the job is small and familiar. A school collects course lists that people typed by hand, one course per line, and wants a short report: how many courses are valid, how many lessons there are in total, which course is the longest, and which courses belong to each level.

Think of a mail room. Letters arrive in all shapes, someone checks each one, unreadable ones go into a separate tray, and only the good ones are counted. The Dart program works in the same three calm stages: parse each line, compute from the good ones, print the report.

Problem → Why → Solution

The problem: a first draft that trusts its input

The first draft most learners write trusts the input completely. It splits each line on semicolons, grabs the second piece and calls int.parse on it. With three perfect lines it works, and the author moves on.

Then a real file arrives. One line has no semicolons at all, another says zero where a number should be, a third has a blank title. The first bad line throws a RangeError or a FormatException, the whole report disappears, and nobody learns which line caused it. Even worse is the version that quietly turns bad values into 0: its total looks fine and is wrong.

naive_total.dart
int totalLessons(List<String> lines) {
  var total = 0;
  for (final line in lines) {
    final parts = line.split(';');
    total += int.parse(parts[1]); // RangeError or FormatException on a bad line
  }
  return total;
}

Why the type checker cannot save you here

Every line is just a String, and a String can hold anything, so the compiler has nothing to complain about. The checking has to be done by your own code, once, at the place where text becomes data. After that point the rest of the program works with a Course whose fields already satisfy the rules, so no other function has to re-check them.

Core concept: build from the inside out

Build a mini project from the inside out: data first, then the edge where raw text enters, then the logic, and main() last. Every stage has one job and one way of failing, which is why bugs have only a few places to hide.

1. Model the data

The Course class has three final fields and a const constructor. Once a line has been parsed, nothing can change its lessons count by accident, and a typo such as course.lesons is a compile error instead of a silent zero.

2. Parse at the boundary

parseCourse takes one String and returns Course?, where null means this line is unusable. It uses int.tryParse, which returns null for bad text instead of throwing. Bad lines in a data file are normal rather than exceptional, so the caller simply counts the rejected ones.

3. Compute with plain functions

summarize, longest and groupByLevel take a list and return a value. They never print and never touch global variables, so you can check each one by calling it with a two-element list.

4. Wire it together in main

main loops over the raw lines, sorts them into accepted courses and rejected lines, calls the functions and prints. If the report looks wrong, you know exactly which stage to open.

Edge cases are decisions, not accidents, so make them while you write. An empty list gives zero courses, zero lessons and an average of 0.0 instead of a division by zero. When two courses tie for longest, the one listed first wins, because the comparison uses a strict greater-than. summarize returns a record with named fields, so three related numbers travel together without a one-off class and are read as stats.total.

SituationDecision
Empty listZero counts and an average of 0.0
Two courses tie for longestThe one listed first wins
Unusable lineSkipped, then counted as rejected
Level typed as Advanced or advancedLowercased once while parsing
A funnel, not a pipe
  1. Raw text lines arrive
  2. Parse: a Course or null
  3. Keep the good, count the rest
  4. Pure functions compute results
  5. main() prints the report

Everything narrows as it moves down: strings become typed values, typed values become numbers, and only the last step touches the console.

General pattern

dart
class Item {
  const Item(this.name, this.count);
  final String name;
  final int count;
}

Item? parseItem(String line) {
  // split, convert with tryParse, validate; return null when unusable
}

({int items, int total}) summarize(List<Item> list) { /* loop, return a record */ }

A small immutable class, one parser that returns a nullable result, and one summary function that returns a record. Swap in your own names and fields and the shape stays the same.

Course catalog report: parse, summarize, group

The program below reads seven raw lines. Three of them are broken on purpose: one has no semicolons, one has the word zero instead of a number, and one has an empty title. Testing and Flutter UI both have 25 lessons, so the output also shows how a tie is settled. Read the code from the top, one function at a time, before you look at the output.

catalog.dart
class Course {
  const Course(this.title, this.lessons, this.level);

  final String title;
  final int lessons;
  final String level;
}

/// Turns one raw "title;lessons;level" line into a Course, or null if unusable.
Course? parseCourse(String line) {
  final parts = line.split(';');
  if (parts.length != 3) return null;

  final title = parts[0].trim();
  final lessons = int.tryParse(parts[1].trim());
  final level = parts[2].trim().toLowerCase();

  if (title.isEmpty || lessons == null || lessons <= 0) return null;
  return Course(title, lessons, level);
}

({int count, int total, double average}) summarize(List<Course> courses) {
  if (courses.isEmpty) return (count: 0, total: 0, average: 0.0);
  var total = 0;
  for (final course in courses) {
    total += course.lessons;
  }
  return (count: courses.length, total: total, average: total / courses.length);
}

Course? longest(List<Course> courses) {
  Course? best;
  for (final course in courses) {
    if (best == null || course.lessons > best.lessons) best = course;
  }
  return best;
}

Map<String, List<Course>> groupByLevel(List<Course> courses) {
  final groups = <String, List<Course>>{};
  for (final course in courses) {
    groups.putIfAbsent(course.level, () => <Course>[]).add(course);
  }
  return groups;
}

void main() {
  const rawLines = [
    'Dart Basics;18;beginner',
    'Flutter UI;25;intermediate',
    'API Integration;12;intermediate',
    'Broken line without separators',
    'Async Dart;zero;advanced',
    '  Testing ; 25 ; Advanced ',
    ';7;beginner',
  ];

  final courses = <Course>[];
  final rejected = <String>[];
  for (final line in rawLines) {
    final course = parseCourse(line);
    if (course == null) {
      rejected.add(line);
    } else {
      courses.add(course);
    }
  }

  final stats = summarize(courses);
  print('Accepted ${stats.count} courses, rejected ${rejected.length}');
  print('Total lessons: ${stats.total}');
  print('Average: ${stats.average.toStringAsFixed(1)} lessons per course');

  final top = longest(courses);
  print('Longest: ${top?.title ?? 'none'}');

  for (final entry in groupByLevel(courses).entries) {
    final titles = entry.value.map((c) => c.title).join(', ');
    print('${entry.key}: $titles');
  }

  print('Empty list -> ${summarize(const []).total} lessons, '
      'longest = ${longest(const [])?.title}');
}

Code breakdown

  1. Immutable dataconst Course(this.title, this.lessons, this.level);

    The initializing formal this.title copies each argument straight into a final field. The const constructor lets you build courses in a const context, and the final fields mean a parsed course can never change afterwards.

  2. Parse without throwingfinal lessons = int.tryParse(parts[1].trim());

    tryParse returns int?: the number, or null when the text is not a whole number. The variable is nullable on purpose and is checked on the very next lines.

  3. One rejection ruleif (title.isEmpty || lessons == null || lessons <= 0) return null;

    Because lessons == null is tested first, the || short-circuits, and lessons <= 0 only runs once lessons is known to be an int. After this line the compiler promotes lessons to int, so Course(title, lessons, level) needs no ! operator.

  4. Record resultreturn (count: courses.length, total: total, average: total / courses.length);

    A record with named fields. The declared return type ({int count, int total, double average}) must match it, and callers read stats.total and stats.average. The empty-list case already returned earlier, so this division is safe.

  5. Tie ruleif (best == null || course.lessons > best.lessons) best = course;

    best starts as null, so the first course always becomes the candidate. After that only a strictly larger course replaces it, which is why Flutter UI beats Testing even though both have 25 lessons.

  6. Groupinggroups.putIfAbsent(course.level, () => <Course>[]).add(course);

    putIfAbsent creates the list the first time a level appears and returns the existing one afterwards, so one line covers both cases. Maps keep insertion order, so levels print in the order they were first seen.

  7. Null-safe printingprint('Longest: ${top?.title ?? 'none'}');

    longest returns Course?. The ?. operator reads title only when top is not null, and ?? supplies the fallback text, so an empty catalog prints none instead of crashing.

You should see
Accepted 4 courses, rejected 3
Total lessons: 80
Average: 20.0 lessons per course
Longest: Flutter UI
beginner: Dart Basics
intermediate: Flutter UI, API Integration
advanced: Testing
Empty list -> 0 lessons, longest = null
Life of one input line
  1. Read a raw line
  2. Split it on semicolons
  3. Convert and validate the parts
  4. Create a Course or return null
  5. Summarize all accepted courses
  6. Print the report

Valid line

Course added to the accepted list

Unusable line

Stored in rejected, run continues

Check edge cases without a framework

Before reaching for package:test, you can check a parser with nothing but a helper function and a list of cases. The snippet below tests a smaller function, parseLessons, with a mix of normal and awkward inputs: spaces, zero, negative numbers, words, decimals, null and an empty string. A failing case prints the expected and the actual value, so you see the problem without a debugger.

checks.dart
int? parseLessons(String? raw) {
  if (raw == null) return null;
  final value = int.tryParse(raw.trim());
  return (value == null || value <= 0) ? null : value;
}

var failures = 0;

void check(String name, Object? actual, Object? expected) {
  final ok = actual == expected;
  if (!ok) failures++;
  print('${ok ? 'PASS' : 'FAIL'}  $name');
  if (!ok) print('      expected $expected but got $actual');
}

void main() {
  check('plain number', parseLessons('18'), 18);
  check('surrounding spaces', parseLessons('  7 '), 7);
  check('zero is rejected', parseLessons('0'), null);
  check('negative is rejected', parseLessons('-3'), null);
  check('words are rejected', parseLessons('many'), null);
  check('decimal is rejected', parseLessons('2.5'), null);
  check('null input', parseLessons(null), null);
  check('empty string', parseLessons(''), null);
  print(failures == 0 ? 'All checks passed' : '$failures check(s) failed');
}

This is the same idea as a unit test file, just smaller. When you move to package:test, which the testing lesson covers, each check() call becomes a test() with an expect(), and dart test runs them all. The habit that matters is writing the awkward cases down at all.

Why a class beats Map<String, dynamic>

A tempting shortcut is to keep every course as a Map<String, dynamic> and read fields with course['lessons'] as int? ?? 0. It runs, but it hides mistakes: a typo such as course['lesons'] silently becomes 0 and the totals are wrong without any error. Every reader also has to remember which keys exist and what type each value has.

A Course class turns the same mistake into a compile error and lets the editor autocomplete the fields. The cost is one small class, paid once, at the boundary where text is parsed. This is also the shape of real apps: JSON arrives as a map, a fromJson step converts it to a typed model, and everything after that works with the model.

In real projects

In real projects

Report scripts, data importers and log summarisers all follow this shape: read raw text, validate each record, compute from the valid ones and print or save the result. The part that changes between projects is the data model; the stages stay the same. A good importer also prints how many records it rejected, because a total that silently ignores bad rows looks complete and is not.

In a Flutter app the same structure appears under different names. A repository fetches JSON, a fromJson factory plays the role of parseCourse, a list of typed models plays the role of courses, and small pure functions prepare the numbers a screen shows. Because those functions have no side effects, they are the easiest part of an app to test, which is why teams keep logic out of widgets and out of main().

Common mistakes

Common mistakes

Using int.parse on untrusted text

int.parse throws a FormatException for anything that is not a whole number, so one bad line aborts the whole run. Use int.tryParse, check for null, and decide what to do with that line. Throwing suits programmer errors, but a typo in a data file is an expected input problem.

Dividing by the length of an empty list

With zero courses, total / courses.length is 0 / 0, and in Dart that is the double NaN rather than an exception. The report would print NaN lessons per course. Check isEmpty before dividing and return a sensible default.

Using >= when looking for the maximum

With >= the last course in a tie replaces the earlier one, so reordering the input changes the answer. Decide the tie rule on purpose: strict > keeps the first, >= keeps the last, and either is fine when it is deliberate and documented.

Printing inside the logic functions

A summarize that prints cannot be reused for a file export or checked by a test, because the result goes to the console instead of back to the caller. Return values, and print only in main().

Mini challenge

Reading tracker: percent done and what to finish next

Write a small reading tracker. Each raw line looks like title|pagesRead|totalPages. Parse the lines into Book objects, reject the unusable ones, print the percent finished for each book and pick the book to finish next.

  • Book is an immutable class with title, pagesRead and totalPages and a percent getter that rounds down
  • parseBook returns null for the wrong number of fields, non-numbers, a zero total or more pages read than pages in total
  • closestToFinished ignores finished books, breaks ties in favour of the earlier book and returns null when nothing qualifies
  • main prints one line per accepted book, the number of rejected lines and the suggestion
tracker.dart
class Book {
  // TODO: const constructor with title, pagesRead, totalPages (all final)
  // TODO: int get percent => whole percent finished, rounded down
}

Book? parseBook(String line) {
  // TODO: split "title|pagesRead|totalPages" on '|'
  // TODO: return null for: wrong field count, blank title, non-numbers,
  //       totalPages <= 0, pagesRead < 0 or pagesRead > totalPages
}

Book? closestToFinished(List<Book> books) {
  // TODO: skip finished books (100%), keep the highest percent,
  //       the earlier book wins ties, null when nothing qualifies
}

void main() {
  const lines = [
    'Dart in Depth|120|300',
    'Effective Dart|90|90',
    'Async Cookbook|150|200',
    'No separators here',
    'Empty Shelf|10|0',
    'Patterns|150|200',
    'Overread|50|40',
    'Fresh Start|0|120',
  ];
  // TODO: parse every line, count the rejected ones, print "<title>: <percent>%"
  // TODO: print "Rejected lines: <n>" and the book to finish next
}

Expected: The five accepted books with their percentages (40, 100, 75, 75, 0), then Rejected lines: 3 and Finish next: Async Cookbook, because it ties with Patterns at 75% and was listed first.

Show hint

Use int.tryParse for both numbers and check each result for null before comparing. For the percent, multiply before dividing: pagesRead * 100 ~/ totalPages avoids decimals.

Show solution
tracker.dart
class Book {
  const Book(this.title, this.pagesRead, this.totalPages);

  final String title;
  final int pagesRead;
  final int totalPages;

  int get percent => pagesRead * 100 ~/ totalPages;
}

Book? parseBook(String line) {
  final fields = line.split('|');
  if (fields.length != 3) return null;

  final title = fields[0].trim();
  final read = int.tryParse(fields[1].trim());
  final total = int.tryParse(fields[2].trim());

  if (title.isEmpty || read == null || total == null) return null;
  if (total <= 0 || read < 0 || read > total) return null;
  return Book(title, read, total);
}

Book? closestToFinished(List<Book> books) {
  Book? best;
  for (final book in books) {
    if (book.percent >= 100) continue;
    if (best == null || book.percent > best.percent) best = book;
  }
  return best;
}

void main() {
  const lines = [
    'Dart in Depth|120|300',
    'Effective Dart|90|90',
    'Async Cookbook|150|200',
    'No separators here',
    'Empty Shelf|10|0',
    'Patterns|150|200',
    'Overread|50|40',
    'Fresh Start|0|120',
  ];

  final books = <Book>[];
  var rejected = 0;
  for (final line in lines) {
    final book = parseBook(line);
    if (book == null) {
      rejected++;
    } else {
      books.add(book);
    }
  }

  for (final book in books) {
    print('${book.title}: ${book.percent}%');
  }
  print('Rejected lines: $rejected');

  final next = closestToFinished(books);
  print(next == null ? 'Nothing left to read' : 'Finish next: ${next.title}');
  print(closestToFinished(const [])?.title ?? 'Empty shelf: no suggestion');
}

Quick quiz 1 / 3

What does parseCourse('Intro;0;beginner') return?

Quick quiz 2 / 3

summarize is called with an empty list and has no early return. What does total / courses.length give when total is 0?

Quick quiz 3 / 3

Flutter UI and Testing both have 25 lessons. Why does the example report Flutter UI as the longest?

What to remember

  • Model the data first with a small immutable class so typos become compile errors
  • Convert text to typed values once, at the boundary, and let null mean unusable
  • Decide edge cases on purpose: empty input, ties and rejected lines
  • Keep logic in pure functions that return values, and let main() wire and print

Dart language overview — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project | Thuta Learning