DART PROGRAMMING COURSE · BRAINBIT INFOTECH

Part 5
Libraries, Tooling and Projects

Module 17: Core Libraries, JSON and Dates

dart:math, dart:convert, DateTime, RegExp, Uri, Stopwatch and reading input · 7 h

Module 18: Packages, Testing and Debugging

pubspec.yaml, pub.dev, imports, unit tests, debugging and clean code · 6 h

Module 19: Data Structures and Algorithms with Dart

Searching, sorting, recursion, stacks, queues, linked lists and Big-O thinking · 7 h

Module 20: Capstone Projects, Best Practices and Career

Put everything together, write clean Dart and plan your next step · 8 h

28 class hours · 40 practice examples · Trainer: Nandan Kumar, Ranchi

MODULE 17 · PART 5

Core Libraries, JSON and Dates

dart:math, dart:convert, DateTime, RegExp, Uri, Stopwatch and reading input
You will learn
  • dart:math: sqrt, pow, min, max, trigonometry and Random
  • dart:convert: JSON encode and decode
  • DateTime and Duration
  • RegExp: find and validate patterns
  • Uri and Stopwatch
  • Reading input with stdin and organising imports
You will build: a JSON profile, a due-date calculator and a phone-number validator
7 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📚

Where is this used in real apps?

Dart comes with a big toolbox called the core libraries. You import what you need: maths, dates, JSON for talking to servers, patterns for validation. Learning the toolbox saves hours of work.

APIs and servers

Every server reply is JSON. jsonDecode turns it into maps and lists.

Fee and due dates

DateTime adds days and finds the difference between dates.

Forms

RegExp checks phone numbers, emails and PIN codes.

Fee Reminder
📅
Due: 15 Dec 2026
DateTime
📞
98001 11111
valid (RegExp)
📄
{"name":"Asha"}
JSON

dart:math

Import with import 'dart:math';. You get sqrt, pow, min, max, pi, sin, cos and Random.

Random: nextInt(6) gives 0 to 5. Add 1 for a dice. Output changes each run.
import 'dart:math';

void main() {
  print(sqrt(256));
  print(pow(3, 4));
  print(max(12, 99));
  print(min(12, 99));
  print(pi.toStringAsFixed(4));
  print(sin(pi / 2));
  var r = Random();
  int dice = r.nextInt(6) + 1;
  print(dice >= 1 && dice <= 6);
}

JSON with dart:convert

JSON is text that looks like maps and lists. jsonEncode turns Dart data into text to send. jsonDecode turns received text back into maps and lists.

Real use: every app-server conversation uses jsonEncode and jsonDecode.
import 'dart:convert';

void main() {
  var student = {'name': 'Asha', 'marks': [90, 80], 'passed': true};
  String text = jsonEncode(student);
  print(text);
  var back = jsonDecode(text);
  print(back['name']);
  print(back['marks'][1]);
  var list = jsonDecode('[1, 2, {"k": "v"}]');
  print(list.length);
}

DateTime and Duration

DateTime(year, month, day) makes a date. add, subtract, difference and isBefore do date maths. Duration is an amount of time.

weekday: 1 = Monday ... 7 = Sunday. Dec 1, 2026 is a Tuesday (2).
void main() {
  var d = DateTime(2026, 12, 1);
  print(d.year);
  print(d.month);
  print(d.weekday);
  var due = d.add(Duration(days: 30));
  print(due.day);
  print(due.month);
  var a = DateTime(2026, 12, 25);
  print(a.difference(d).inDays);
  print(d.isBefore(a));
}

RegExp

A regular expression describes a pattern. hasMatch tests, firstMatch and allMatches find. Handy: \d digit, + one or more, ^ start, $ end, [a-z] range.

Indian mobile numbers start with 6, 7, 8 or 9 and have 10 digits.
void main() {
  var phone = RegExp(r'^[6-9]\d{9}$');
  print(phone.hasMatch('9876543210'));
  print(phone.hasMatch('12345'));
  var digits = RegExp(r'\d+');
  print(digits.allMatches('Room 12, floor 3').map((m) => m.group(0)).toList());
  print('a1b22c333'.replaceAll(RegExp(r'\d'), '#'));
  var pin = RegExp(r'^\d{6}$');
  print(pin.hasMatch('834001'));
}

Uri and Stopwatch

Uri.parse splits a web address into parts. Stopwatch measures how long code takes.

Timing: the number of milliseconds is different on every computer, so we print only a check.
void main() {
  var u = Uri.parse('https://brainbit-teaching.com/courses?topic=dart&level=1');
  print(u.scheme);
  print(u.host);
  print(u.path);
  print(u.queryParameters['topic']);
  print(u.queryParameters);
  var sw = Stopwatch()..start();
  int s = 0;
  for (int i = 0; i < 100000; i++) { s += i; }
  sw.stop();
  print(s);
  print(sw.elapsedMilliseconds >= 0);
}

Reading input with stdin

In a real command-line program use stdin.readLineSync() (needs import 'dart:io'). It returns text or null. In the slides below the typed answers are simulated so you can see the output.

Try on your computer: save this file and run dart run file.dart, then type the answers.
import 'dart:io';

void main() {
  stdout.write('Enter your name: ');
  String? name = stdin.readLineSync();
  stdout.write('Enter marks: ');
  int marks = int.parse(stdin.readLineSync() ?? '0');
  print('Hello $name, marks: $marks');
  print(marks >= 33 ? 'PASS' : 'FAIL');
}

Animated explainer: JSON round trip

Press Next to walk through it step by step, or Auto play.

Animated explainer: Reading a RegExp

Press Next to walk through it step by step, or Auto play.
EASYReal project: games and quizzesExample 1 of 10

Dice and random

A Random object picks numbers. Output differs each run; we also show the guaranteed range.
import 'dart:math';

void main() {
  var r = Random();
  int dice = r.nextInt(6) + 1;
  print('You rolled a number from 1 to 6: ${dice >= 1 && dice <= 6}');
  var picks = List.generate(5, (_) => r.nextInt(100));
  print('Five picks, all below 100: ${picks.every((p) => p < 100)}');
}
Try it yourself: Pick a random day name from a list.
days[r.nextInt(days.length)]
EASYReal project: geometry and constructionExample 2 of 10

Hypotenuse

Pythagoras with sqrt and pow.
import 'dart:math';

void main() {
  double a = 6, b = 8;
  double c = sqrt(pow(a, 2) + pow(b, 2));
  print('Hypotenuse = $c');
  print('Area of circle r=5: ${(pi * 5 * 5).toStringAsFixed(2)}');
}
Try it yourself: Find the hypotenuse for 5 and 12.
Change a and b.
EASYReal project: sending data to a serverExample 3 of 10

Encode to JSON

jsonEncode makes text from a map.
import 'dart:convert';

void main() {
  var order = {'id': 1042, 'item': 'Notebook', 'qty': 5, 'paid': true};
  print(jsonEncode(order));
  print(jsonEncode([1, 2, 3]));
  print(jsonEncode('plain text'));
}
Try it yourself: Encode your own profile.
Make a map.
EASYReal project: reading a server replyExample 4 of 10

Decode JSON

jsonDecode gives back maps and lists you can use.
import 'dart:convert';

void main() {
  String reply = '{"city":"Ranchi","temp":24,"tags":["clear","dry"]}';
  var data = jsonDecode(reply);
  print('City: ${data['city']}');
  print('Temp: ${data['temp']} C');
  print('First tag: ${data['tags'][0]}');
}
Try it yourself: Read the second tag.
data['tags'][1]
EASYReal project: age and birthday calculatorsExample 5 of 10

Date parts

A DateTime exposes year, month, day and weekday.
void main() {
  var d = DateTime(2026, 8, 15);
  print('${d.day}/${d.month}/${d.year}');
  print('Weekday number: ${d.weekday}');
  var names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  print('Day: ${names[d.weekday - 1]}');
}
Try it yourself: Use your birthday.
DateTime(year, month, day)
MEDIUMReal project: school fee remindersExample 6 of 10

Fee due date

Add days to a date and compare. difference().inDays counts the gap.
void main() {
  var admission = DateTime(2026, 7, 1);
  var due = admission.add(Duration(days: 45));
  var today = DateTime(2026, 8, 20);
  print('Due on: ${due.day}/${due.month}/${due.year}');
  int daysLate = today.difference(due).inDays;
  print(daysLate > 0 ? 'Late by $daysLate days' : 'On time');
  print('Late fee: Rs ${daysLate > 0 ? daysLate * 10 : 0}');
}
Try it yourself: Change today to 10 August.
DateTime(2026, 8, 10)
MEDIUMReal project: sign-up and address formsExample 7 of 10

Phone and PIN validator

RegExp patterns validate formats quickly.
void main() {
  var phone = RegExp(r'^[6-9]\d{9}$');
  var pin = RegExp(r'^\d{6}$');
  for (var p in ['9876543210', '1234567890', '98765']) {
    print('$p -> ${phone.hasMatch(p) ? 'valid' : 'invalid'}');
  }
  print('834001 pin: ${pin.hasMatch('834001')}');
  print('83400 pin : ${pin.hasMatch('83400')}');
}
Try it yourself: Add a check for 5-digit house numbers.
RegExp(r'^\d{5}$')
MEDIUMReal project: reading amounts from SMSExample 8 of 10

Extract numbers from text

allMatches finds every number in a message.
void main() {
  String sms = 'Rs 2500 debited, balance Rs 14320 on 05-12-2026';
  var nums = RegExp(r'\d+').allMatches(sms).map((m) => m.group(0)!).toList();
  print(nums);
  int first = int.parse(nums.first);
  print('Debited: $first');
  var email = RegExp(r'[a-z.]+@[a-z]+\.[a-z]+');
  print(email.firstMatch('mail asha.k@example.com now')?.group(0));
}
Try it yourself: Find all words starting with R.
RegExp(r'R\w+')
HARDReal project: turning server data into objectsExample 9 of 10

JSON model with fromJson

The standard pattern in every app: a class with fromJson and toJson.
import 'dart:convert';

class Student {
  final String name;
  final int marks;
  Student(this.name, this.marks);
  factory Student.fromJson(Map<String, dynamic> j) => Student(j['name'] as String, j['marks'] as int);
  Map<String, dynamic> toJson() => {'name': name, 'marks': marks};
}

void main() {
  String reply = '[{"name":"Asha","marks":91},{"name":"Rohit","marks":67}]';
  var list = (jsonDecode(reply) as List).map((e) => Student.fromJson(e)).toList();
  for (var s in list) {
    print('${s.name}: ${s.marks}');
  }
  print(jsonEncode(list.map((s) => s.toJson()).toList()));
}
Try it yourself: Add a city field to the model.
Add it in the class, fromJson and toJson.
HARDReal project: command-line programsExample 10 of 10

Console input simulation

This is a real stdin program. On the slide the typed answers are simulated; on your computer you type them.
Pretend the user types: Asha , 88 , 92
import 'dart:io';

void main() {
  stdout.write('Student name: ');
  String name = stdin.readLineSync() ?? 'Unknown';
  stdout.write('Maths marks: ');
  int m = int.tryParse(stdin.readLineSync() ?? '') ?? 0;
  stdout.write('Science marks: ');
  int s = int.tryParse(stdin.readLineSync() ?? '') ?? 0;
  print('');
  print('Result for $name');
  print('Total: ${m + s}/200  Percent: ${(m + s) / 2}%');
}
Try it yourself: Add an English marks question.
Copy the stdout.write and readLineSync lines.

Quick quiz

3 questions. Click an answer.
Which function turns a Dart map into JSON text?
jsonDecodejsonEncodetoStringparse
What does DateTime.weekday return for Monday?
017Mon
What does ^ mean in a RegExp?
Any digitStart of the textEnd of the textA space
Score: 0 / 3

Recap: what you learned in Module 17

dart:math

sqrt, pow, min, max, pi, Random.

JSON

jsonEncode to send, jsonDecode to receive.

DateTime

add, difference, isBefore, weekday.

RegExp

Validate and extract patterns.

Uri / Stopwatch

Split links; measure time.

stdin

readLineSync reads typed input in console programs.

Next: Packages, Testing and Debugging - pubspec.yaml, pub.dev, imports, unit tests, debugging and clean code
MODULE 18 · PART 5

Packages, Testing and Debugging

pubspec.yaml, pub.dev, imports, unit tests, debugging and clean code
You will learn
  • Anatomy of a Dart project and pubspec.yaml
  • Packages from pub.dev and pub get
  • Imports: as, show, hide and your own files
  • Unit tests: expect, group and test
  • Debugging: print, assert and the debugger
  • Clean code: naming, dart format and dart analyze
You will build: a tested price calculator, a mini test runner and a bug-hunting checklist
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🔧

Where is this used in real apps?

Real projects are folders with many files, outside packages and automatic tests. Tests are small programs that check your code still works after every change. Debugging is the skill of finding why it does not.

Software companies

No code is accepted without tests. Tests catch bugs before customers do.

Open-source packages

http, intl, provider and thousands more are one line away.

Teams

Clean names, format and analyze keep many developers on one codebase.

Test Results
✅
price calculator
12 tests passed
✅
validators
8 tests passed
❌
discount rule
1 test failed

Project structure

dart create my_app makes this layout. bin/ holds the program entry, lib/ your reusable code, test/ your tests, and pubspec.yaml describes the project.

Rule: put logic in lib/ so both bin/ and test/ can reuse it.
my_app/
  pubspec.yaml        <- name, version, packages used
  analysis_options.yaml
  bin/
    my_app.dart       <- main() starts here
  lib/
    calculator.dart   <- your own reusable code
    models/
      student.dart
  test/
    calculator_test.dart
  README.md

pubspec.yaml and packages

List packages under dependencies. Run dart pub get to download them. Search packages on pub.dev. Use dart pub add http as a shortcut.

Version rule: ^1.2.0 means "1.2.0 or newer, but below 2.0.0".
name: school_tools
description: Tools for school fees
version: 1.0.0

environment:
  sdk: ^3.5.0

dependencies:
  http: ^1.2.0      # call web servers
  intl: ^0.19.0     # dates and rupee formatting

dev_dependencies:
  test: ^1.25.0     # unit tests
  lints: ^4.0.0

Imports in detail

import 'dart:...' for the Dart SDK, import 'package:name/file.dart' for packages, and import 'models/student.dart' for your own files. as renames, show picks, hide excludes.

as avoids clashes when two libraries have the same name.
import 'dart:math' as m;
import 'dart:convert' show jsonEncode;

void main() {
  print(m.sqrt(49));
  print(m.max(3, 8));
  print(jsonEncode({'ok': true}));
}
// Other forms (not runnable here):
// import 'package:http/http.dart' as http;
// import 'dart:math' hide Random;
// import 'models/student.dart';

Unit tests with package:test

A test calls your code and uses expect(actual, expected). Run all tests with dart test. Group related tests with group. (This needs the test package, so this slide is not run here; the next slide builds a mini version you can run.)

Good tests: small, one idea each, named like a sentence.
import 'package:test/test.dart';
import 'package:school_tools/fee.dart';

void main() {
  group('late fee', () {
    test('no fee when paid on time', () {
      expect(lateFee(0), 0);
    });
    test('Rs 10 per day after due date', () {
      expect(lateFee(5), 50);
    });
    test('fee is capped at Rs 500', () {
      expect(lateFee(100), 500);
    });
  });
}
// run:  dart test

A mini test runner you can run

The idea behind every test framework is simple. A test function runs a check and prints pass or fail. Here is a tiny one built from what you already know.

The last test fails on purpose. Tests exist to show you exactly such mistakes.
int passed = 0, failed = 0;
void test(String name, void Function() body) {
  try {
    body();
    passed++;
    print('PASS  $name');
  } catch (e) {
    failed++;
    print('FAIL  $name -> $e');
  }
}
void expect(Object? actual, Object? expected) {
  if (actual != expected) throw 'expected $expected but got $actual';
}
int lateFee(int days) => days <= 0 ? 0 : (days * 10 > 500 ? 500 : days * 10);
void main() {
  test('on time', () => expect(lateFee(0), 0));
  test('cap', () => expect(lateFee(100), 500));
  test('wrong on purpose', () => expect(lateFee(2), 30));
  print('$passed passed, $failed failed');
}

Debugging

Four tools: 1) print values to see what the program really does, 2) assert to check your assumptions, 3) the debugger in VS Code (breakpoints, step over, watch variables), 4) read the error message and line number.

VS Code: click left of a line number for a red breakpoint, press F5, then F10 to step through code.
int average(List<int> marks) {
  int total = 0;
  for (var m in marks) {
    total += m;
    print('DEBUG: added $m, total now $total');
  }
  assert(marks.isNotEmpty, 'marks must not be empty');
  return total ~/ marks.length;
}

void main() {
  print(average([70, 80, 90]));
}

Animated explainer: Test-driven loop

Press Next to walk through it step by step, or Auto play.

Animated explainer: Bug hunting steps

Press Next to walk through it step by step, or Auto play.
EASYReal project: checking a calculationExample 1 of 10

Test one function

The simplest test: compare the result with the answer you know is right.
int square(int n) => n * n;

void main() {
  print(square(5) == 25 ? 'PASS' : 'FAIL');
  print(square(-3) == 9 ? 'PASS' : 'FAIL');
  print(square(0) == 0 ? 'PASS' : 'FAIL');
}
Try it yourself: Add a test for square(10).
print(square(10) == 100 ? ...)
EASYReal project: finding why a total is wrongExample 2 of 10

Print debugging

Print inside the loop to watch the values change.
void main() {
  var prices = [100, 250, 80];
  int total = 0;
  for (var p in prices) {
    total += p;
    print('added $p -> total $total');
  }
  print('Final: $total');
}
Try it yourself: Find the bug if one price were negative.
Change a price to -80 and watch.
EASYReal project: catching wrong inputs earlyExample 3 of 10

assert for assumptions

assert stops the program in debug mode when an assumption is false.
double percent(int marks, int total) {
  assert(total > 0, 'total must be positive');
  return marks / total * 100;
}

void main() {
  print(percent(45, 50));
  try {
    print(percent(10, 0));
  } catch (e) {
    print('Assertion caught');
  }
}
Try it yourself: Add an assert that marks <= total.
assert(marks <= total);
EASYReal project: avoiding name clashesExample 4 of 10

Alias import

Use as to keep library names short and clear.
import 'dart:math' as math;

void main() {
  print(math.sqrt(144));
  print(math.pow(2, 8));
  print(math.min(4, 9));
}
Try it yourself: Use math.pi.
math.pi
EASYReal project: keeping code tidyExample 5 of 10

Show only what you need

show imports only the names you list.
import 'dart:convert' show jsonEncode, jsonDecode;
import 'dart:math' show max, min;

void main() {
  print(max(3, 7));
  print(min(3, 7));
  print(jsonEncode([1, 2]));
  print(jsonDecode('{"a":1}'));
}
Try it yourself: Also show sqrt from dart:math.
show max, min, sqrt
MEDIUMReal project: a team's unit testsExample 6 of 10

Mini test suite

A tiny test framework plus three tests on a price function. Same ideas as package:test.
void check(String name, bool ok) => print('${ok ? 'PASS' : 'FAIL'}  $name');

double price(double mrp, double discountPct) => mrp - mrp * discountPct / 100;

void main() {
  check('no discount', price(1000, 0) == 1000);
  check('10 percent', price(1000, 10) == 900);
  check('half price', price(800, 50) == 400);
  check('full discount', price(500, 100) == 0);
}
Try it yourself: Add a test for 25 percent of 2000.
check('25%', price(2000, 25) == 1500);
MEDIUMReal project: form validation rulesExample 7 of 10

Testing validators

Test valid and invalid inputs. Good tests cover both.
bool validPin(String s) => RegExp(r'^\d{6}$').hasMatch(s);

void expectTrue(String label, bool v) => print('${v ? 'PASS' : 'FAIL'}  $label');

void main() {
  expectTrue('valid 834001', validPin('834001'));
  expectTrue('too short', !validPin('8340'));
  expectTrue('letters', !validPin('83400a'));
  expectTrue('seven digits', !validPin('8340011'));
  expectTrue('empty', !validPin(''));
}
Try it yourself: Add a test with spaces.
expectTrue('space', !validPin('834 01'));
MEDIUMReal project: real debugging practiceExample 8 of 10

Find the bug

The function has a logic bug. The tests reveal it and the print shows the cause.
double average(List<int> marks) {
  int total = 0;
  for (int i = 0; i < marks.length - 1; i++) {
    total += marks[i];
  }
  return total / marks.length;
}

void main() {
  var marks = [60, 70, 80];
  print('Expected 70.0, got ${average(marks)}');
  print(average(marks) == 70 ? 'PASS' : 'FAIL - the last mark is skipped!');
}
Try it yourself: Fix the loop condition.
Use i < marks.length instead.
HARDReal project: organising many testsExample 9 of 10

Test runner with groups

Groups, a counter and a summary: a real framework in 25 lines.
int passed = 0, failed = 0;
void group(String name, void Function() body) {
  print('== $name ==');
  body();
}
void test(String name, bool ok) {
  if (ok) { passed++; } else { failed++; }
  print('  ${ok ? 'PASS' : 'FAIL'}  $name');
}
int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);
bool isPrime(int n) => n > 1 && List.generate(n, (i) => i).skip(2).every((d) => n % d != 0);
void main() {
  group('gcd', () {
    test('12 and 18', gcd(12, 18) == 6);
    test('coprime', gcd(7, 13) == 1);
  });
  group('isPrime', () {
    test('2 is prime', isPrime(2));
    test('1 is not prime', !isPrime(1));
    test('91 is not prime', !isPrime(91));
  });
  print('Summary: $passed passed, $failed failed');
}
Try it yourself: Add a group for even numbers.
group('even', () {...});
HARDReal project: testing business rules before shippingExample 10 of 10

Bank account with tests

A class and its tests together. Every rule (deposit, withdraw, overdraft) has a test.
class Account {
  double balance;
  Account(this.balance);
  void deposit(double a) {
    if (a <= 0) throw ArgumentError('Invalid amount');
    balance += a;
  }
  void withdraw(double a) {
    if (a > balance) throw StateError('Insufficient funds');
    balance -= a;
  }
}
bool throwsError(void Function() f) {
  try { f(); return false; } catch (e) { return true; }
}
void test(String n, bool ok) => print('${ok ? 'PASS' : 'FAIL'}  $n');
void main() {
  var a = Account(1000);
  a.deposit(500);
  test('deposit adds', a.balance == 1500);
  a.withdraw(200);
  test('withdraw subtracts', a.balance == 1300);
  test('overdraft throws', throwsError(() => a.withdraw(5000)));
  test('negative deposit throws', throwsError(() => a.deposit(-5)));
  test('balance unchanged after errors', a.balance == 1300);
}
Try it yourself: Add a test for withdrawing exactly the balance.
a.withdraw(a.balance); test(...a.balance == 0);

Quick quiz

3 questions. Click an answer.
Which file lists the packages a Dart project uses?
main.dartpubspec.yamlREADME.mdtest.dart
Which command downloads the packages?
dart rundart testdart pub getdart format
What does expect(actual, expected) do in a test?
Prints textChecks that the result matches the expected valueImports a packageDeletes the test
Score: 0 / 3

Recap: what you learned in Module 18

Project layout

bin, lib, test and pubspec.yaml.

Packages

pub.dev, dependencies, dart pub get.

Imports

dart:, package: and file imports; as, show, hide.

Tests

test, group and expect; dart test.

Debug

print, assert, breakpoints, read errors.

Clean code

Clear names, dart format, dart analyze.

Next: Data Structures and Algorithms with Dart - Searching, sorting, recursion, stacks, queues, linked lists and Big-O thinking
MODULE 19 · PART 5

Data Structures and Algorithms with Dart

Searching, sorting, recursion, stacks, queues, linked lists and Big-O thinking
You will learn
  • What an algorithm is and how to measure it (Big-O idea)
  • Linear and binary search
  • Sorting: bubble, selection and insertion
  • Recursion: factorial, fibonacci, Tower of Hanoi
  • Stack, queue and linked list
  • Hashing with maps: counting, grouping and two-sum
You will build: a roll-number finder, a sorting visualiser and a bracket checker
7 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🧠

Where is this used in real apps?

An algorithm is a clear set of steps to solve a problem. Good algorithms make apps fast: searching one name among a million students in 20 steps instead of a million.

Search bars

Binary search finds a name in a sorted list of millions in about 20 steps.

Undo and browser back

A stack remembers the last actions.

Interviews and exams

Companies test these ideas in every coding round.

Student Finder
🔍
Find roll 4821
13 steps
🔄
Sort by marks
bubble / insertion
↩
Undo last edit
stack pop

Algorithms and Big-O idea

We compare algorithms by how the work grows as data grows. O(1) = same work always. O(n) = work grows with the list. O(log n) = doubles the data, adds one step. O(n squared) = loops inside loops, slow for big data.

O(1) constant

Reading list[5]. Always instant.

O(log n)

Binary search: 1,000,000 items need about 20 steps.

O(n)

Linear search: up to 1,000,000 steps for 1,000,000 items.

O(n squared)

Bubble sort on 1,000,000 items is hopeless.

Idea only: we do not need maths here, just the habit of asking "what if the list is 1000 times bigger?"

Linear and binary search

Linear: check items one by one. Works on any list. Binary: needs a sorted list; check the middle, throw away half, repeat.

Binary search halves the work each time, but only works on sorted data.
int linear(List<int> a, int x) {
  for (int i = 0; i < a.length; i++) {
    if (a[i] == x) return i;
  }
  return -1;
}
int binary(List<int> a, int x) {
  int lo = 0, hi = a.length - 1, steps = 0;
  while (lo <= hi) {
    steps++;
    int mid = (lo + hi) ~/ 2;
    if (a[mid] == x) { print('found in $steps steps'); return mid; }
    if (a[mid] < x) { lo = mid + 1; } else { hi = mid - 1; }
  }
  return -1;
}
void main() {
  var a = [3, 8, 15, 22, 31, 47, 56, 64, 79, 90];
  print(linear(a, 47));
  print(binary(a, 47));
  print(binary(a, 50));
}

Sorting: bubble sort

Bubble sort compares neighbours and swaps them if they are in the wrong order. Repeat until no swaps. Simple but slow: good for learning.

After each pass the biggest number "bubbles" to the end.
List<int> bubble(List<int> a) {
  var x = [...a];
  for (int i = 0; i < x.length - 1; i++) {
    bool swapped = false;
    for (int j = 0; j < x.length - 1 - i; j++) {
      if (x[j] > x[j + 1]) {
        (x[j], x[j + 1]) = (x[j + 1], x[j]);
        swapped = true;
      }
    }
    print('pass ${i + 1}: $x');
    if (!swapped) break;
  }
  return x;
}

void main() {
  print(bubble([5, 2, 9, 1, 6]));
}

Selection and insertion sort

Selection: find the smallest, put it first, repeat. Insertion: take each item and slide it left into the right place, like arranging playing cards in your hand.

In real projects just call list.sort(). Writing sorts yourself teaches how it works.
List<int> selection(List<int> a) {
  var x = [...a];
  for (int i = 0; i < x.length - 1; i++) {
    int m = i;
    for (int j = i + 1; j < x.length; j++) { if (x[j] < x[m]) m = j; }
    (x[i], x[m]) = (x[m], x[i]);
  }
  return x;
}
List<int> insertion(List<int> a) {
  var x = [...a];
  for (int i = 1; i < x.length; i++) {
    int k = x[i], j = i - 1;
    while (j >= 0 && x[j] > k) { x[j + 1] = x[j--]; }
    x[j + 1] = k;
  }
  return x;
}
void main() {
  print(selection([64, 25, 12, 22, 11]));
  print(insertion([64, 25, 12, 22, 11]));
}

Recursion: Hanoi and friends

Recursion solves a big problem by solving smaller copies of it. Tower of Hanoi: to move n discs, move n-1 away, move the last, move n-1 back on top.

n discs need 2 to the power n minus 1 moves: 3 discs = 7 moves.
int moves = 0;
void hanoi(int n, String from, String to, String via) {
  if (n == 0) return;
  hanoi(n - 1, from, via, to);
  moves++;
  print('Move disc $n from $from to $to');
  hanoi(n - 1, via, to, from);
}

void main() {
  hanoi(3, 'A', 'C', 'B');
  print('Total moves: $moves');
}

Stack, queue, linked list

Stack: last in, first out (plates). Queue: first in, first out (ticket line). Linked list: nodes each pointing to the next one.

Real use: stack = undo; queue = print jobs; linked list = music playlist order.
class Node {
  int value;
  Node? next;
  Node(this.value);
}
void main() {
  var stack = <int>[];
  stack..add(1)..add(2)..add(3);
  print(stack.removeLast());
  var queue = <int>[1, 2, 3];
  print(queue.removeAt(0));
  var head = Node(10);
  head.next = Node(20);
  head.next!.next = Node(30);
  Node? cur = head;
  var out = <int>[];
  while (cur != null) {
    out.add(cur.value);
    cur = cur.next;
  }
  print(out);
}

Animated explainer: Binary search: halve every time

Press Next to walk through it step by step, or Auto play.

Animated explainer: Bubble sort pass

Press Next to walk through it step by step, or Auto play.
EASYReal project: attendance and student lookupExample 1 of 10

Find a roll number

Linear search checks items in order and returns the position or -1.
int find(List<int> rolls, int x) {
  for (int i = 0; i < rolls.length; i++) {
    if (rolls[i] == x) return i;
  }
  return -1;
}

void main() {
  var rolls = [101, 105, 109, 112, 118];
  print(find(rolls, 112));
  print(find(rolls, 120));
}
Try it yourself: Search for 101.
find(rolls, 101)
EASYReal project: top score and highest priceExample 2 of 10

Find the maximum

Keep the best value seen so far while looping.
int maxOf(List<int> a) {
  int best = a.first;
  for (var x in a) {
    if (x > best) best = x;
  }
  return best;
}

void main() {
  print(maxOf([45, 91, 12, 77, 63]));
  print(maxOf([-5, -2, -9]));
}
Try it yourself: Write minOf.
Use x < best.
EASYReal project: undo history and reverse readingExample 3 of 10

Reverse a list

Swap from both ends toward the middle.
void main() {
  var a = [1, 2, 3, 4, 5];
  int i = 0, j = a.length - 1;
  while (i < j) {
    (a[i], a[j]) = (a[j], a[i]);
    i++;
    j--;
  }
  print(a);
}
Try it yourself: Reverse a list of 6 numbers.
Add one more number.
EASYReal project: word counts and vote countingExample 4 of 10

Count frequencies

A map counts how many times each item appears.
void main() {
  var votes = ['A', 'B', 'A', 'C', 'A', 'B'];
  var count = <String, int>{};
  for (var v in votes) {
    count[v] = (count[v] ?? 0) + 1;
  }
  print(count);
  var winner = count.entries.reduce((a, b) => a.value >= b.value ? a : b);
  print('Winner: ${winner.key} with ${winner.value}');
}
Try it yourself: Add more votes.
Add letters to votes.
EASYReal project: validating data before binary searchExample 5 of 10

Is sorted?

Compare each item with the next one.
bool isSorted(List<int> a) {
  for (int i = 0; i < a.length - 1; i++) {
    if (a[i] > a[i + 1]) return false;
  }
  return true;
}

void main() {
  print(isSorted([1, 3, 5, 9]));
  print(isSorted([1, 5, 3, 9]));
}
Try it yourself: Check a descending list.
Use a list like [9, 7, 5].
MEDIUMReal project: fast lookup in large sorted dataExample 6 of 10

Binary search with steps

Count the steps to see why binary search is so fast.
int binarySearch(List<int> a, int x) {
  int lo = 0, hi = a.length - 1, steps = 0;
  while (lo <= hi) {
    steps++;
    int mid = (lo + hi) ~/ 2;
    if (a[mid] == x) {
      print('Found $x at index $mid in $steps steps');
      return mid;
    }
    if (a[mid] < x) { lo = mid + 1; } else { hi = mid - 1; }
  }
  print('$x not found after $steps steps');
  return -1;
}

void main() {
  var big = List.generate(1000, (i) => i * 2);
  binarySearch(big, 778);
  binarySearch(big, 1998);
  binarySearch(big, 777);
}
Try it yourself: Search a list of 100000 numbers.
List.generate(100000, (i) => i * 2)
MEDIUMReal project: sorting small lists in appsExample 7 of 10

Insertion sort

Like sorting playing cards: pick one and slide it into place.
List<int> insertionSort(List<int> a) {
  var x = [...a];
  for (int i = 1; i < x.length; i++) {
    int key = x[i];
    int j = i - 1;
    while (j >= 0 && x[j] > key) {
      x[j + 1] = x[j];
      j--;
    }
    x[j + 1] = key;
    print('step $i: $x');
  }
  return x;
}

void main() {
  print(insertionSort([7, 3, 9, 1, 5]));
}
Try it yourself: Sort in descending order.
Use x[j] < key.
MEDIUMReal project: code editors and calculatorsExample 8 of 10

Bracket checker

A stack checks that every opening bracket has the right closing bracket.
bool balanced(String s) {
  var stack = <String>[];
  var pairs = {')': '(', ']': '[', '}': '{'};
  for (var ch in s.split('')) {
    if (pairs.containsValue(ch)) {
      stack.add(ch);
    } else if (pairs.containsKey(ch)) {
      if (stack.isEmpty || stack.removeLast() != pairs[ch]) return false;
    }
  }
  return stack.isEmpty;
}

void main() {
  for (var t in ['(a+b)*[c-d]', '((a+b)', '{[()]}', '([)]']) {
    print('$t -> ${balanced(t)}');
  }
}
Try it yourself: Test the text '{(}'.
Add it to the list.
HARDReal project: interview classic: find pairs quicklyExample 9 of 10

Two-sum with a map

Instead of two loops (slow) a map remembers numbers seen so far (fast).
List<int>? twoSum(List<int> a, int target) {
  var seen = <int, int>{};
  for (int i = 0; i < a.length; i++) {
    int need = target - a[i];
    if (seen.containsKey(need)) return [seen[need]!, i];
    seen[a[i]] = i;
  }
  return null;
}

void main() {
  print(twoSum([2, 7, 11, 15], 9));
  print(twoSum([3, 2, 4], 6));
  print(twoSum([1, 2, 3], 99));
}
Try it yourself: Find the pair that adds to 26.
twoSum([2, 7, 11, 15], 26)
HARDReal project: playlists and navigation chainsExample 10 of 10

Linked list with insert and print

Nodes pointing to nodes. Inserting at the front needs only two changes, unlike a list.
class Node {
  String song;
  Node? next;
  Node(this.song, [this.next]);
}
class Playlist {
  Node? head;
  void addFront(String s) => head = Node(s, head);
  void addEnd(String s) {
    if (head == null) { head = Node(s); return; }
    var cur = head!;
    while (cur.next != null) { cur = cur.next!; }
    cur.next = Node(s);
  }
  void show() {
    var parts = <String>[];
    for (var c = head; c != null; c = c.next) { parts.add(c.song); }
    print('${parts.join(' -> ')}  (${parts.length} songs)');
  }
}
void main() {
  var p = Playlist();
  p.addEnd('Kesariya');
  p.addEnd('Chaiyya Chaiyya');
  p.addFront('Vande Mataram');
  p.show();
}
Try it yourself: Add a method that counts nodes.
Walk the nodes and count.

Quick quiz

3 questions. Click an answer.
Which search needs a SORTED list?
Linear searchBinary searchBothNeither
What is the order of removal in a stack?
First in, first outLast in, first outRandomSorted
What must every recursive function have?
A loopA base caseA listA map
Score: 0 / 3

Recap: what you learned in Module 19

Big-O idea

Ask how work grows when data grows.

Search

Linear checks all; binary halves a sorted list.

Sorting

Bubble, selection, insertion: learn; list.sort() in real code.

Recursion

Smaller copies of the same problem and a base case.

Stack/queue/list

LIFO, FIFO and linked nodes.

Maps

Counting and two-sum in one pass.

Next: Capstone Projects, Best Practices and Career - Put everything together, write clean Dart and plan your next step
MODULE 20 · PART 5

Capstone Projects, Best Practices and Career

Put everything together, write clean Dart and plan your next step
You will learn
  • Plan a project from idea to finished program
  • Combine classes, collections, errors, async and JSON
  • Follow Effective Dart habits
  • Share work with Git and a README
  • Know your career options after Dart
You will build: six portfolio projects and a certificate-ready portfolio
8 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎓

Where is this used in real apps?

You now know the whole language. A project is where it all joins together. Employers and clients judge you by what you built, not by what you studied.

Portfolio

Six working projects with a README prove your skill.

Interviews

You can explain how and why your program is built.

Freelance

Local shops and schools need small tools. Your projects are the samples.

My Portfolio
🎓
Student Grade Book
Dart console
🛒
Shop Billing
Dart console
🏦
Bank Simulator
Dart console

A project skeleton

Most programs share one shape: data classes, logic functions, a report/print part and a small main that connects them. Keep each part separate and testing becomes easy.

Data (Student), logic (gradeOf), report, main: four small parts.
class Student {
  final String name;
  final List<int> marks;
  Student(this.name, this.marks);
  int get total => marks.fold(0, (a, b) => a + b);
  double get percent => total / marks.length;
}
String gradeOf(double p) => switch (p) {
  >= 90 => 'A+',
  >= 75 => 'A',
  >= 60 => 'B',
  >= 33 => 'C',
  _ => 'Fail',
};
void report(List<Student> list) {
  var sorted = [...list]..sort((a, b) => b.total.compareTo(a.total));
  for (int i = 0; i < sorted.length; i++) {
    var s = sorted[i];
    print('#${i + 1} ${s.name.padRight(6)} ${s.total} ${s.percent.toStringAsFixed(1)}% ${gradeOf(s.percent)}');
  }
}
void main() {
  report([Student('Asha', [91, 88, 95]), Student('Rohit', [67, 72, 58]), Student('Meena', [40, 35, 30])]);
}

Validate input and handle errors

Never trust data. Check ranges, handle missing items and use custom exceptions so errors have clear names.

Real projects reject bad input at the door, not deep inside the code.
class InvalidMarks implements Exception {
  final int value;
  InvalidMarks(this.value);
  @override
  String toString() => 'Marks must be 0 to 100, got $value';
}
int checkedMarks(int m) {
  if (m < 0 || m > 100) throw InvalidMarks(m);
  return m;
}
void main() {
  for (var m in [78, 105, -4, 100]) {
    try {
      print('OK ${checkedMarks(m)}');
    } on InvalidMarks catch (e) {
      print('Rejected: $e');
    }
  }
}

Save and load with JSON

Programs forget everything when they stop. Saving as JSON lets data survive. Here we encode and decode in memory; with dart:io you would write the text to a file.

With files: File('stock.json').writeAsStringSync(saved) and readAsStringSync() (needs dart:io; run on your computer).
import 'dart:convert';

class Item {
  String name;
  int qty;
  Item(this.name, this.qty);
  Map<String, dynamic> toJson() => {'name': name, 'qty': qty};
  factory Item.fromJson(Map<String, dynamic> j) => Item(j['name'], j['qty']);
}

void main() {
  var stock = [Item('Rice', 40), Item('Dal', 12)];
  String saved = jsonEncode(stock.map((i) => i.toJson()).toList());
  print(saved);
  var loaded = (jsonDecode(saved) as List).map((e) => Item.fromJson(e)).toList();
  print('${loaded.length} items loaded, first: ${loaded.first.name}');
}

Refactor: make it cleaner

Refactoring means improving code without changing what it does. Rename unclear variables, split long functions, remove repeated code.

Test first: the BEFORE and AFTER give the same answer for 1000 at 18 percent.
// BEFORE: unclear and repeated
double f(double a, double b) {
  return a + a * b / 100;
}

// AFTER: clear names, one job each
double addPercent(double amount, double percent) => amount + amount * percent / 100;
double withGst(double price) => addPercent(price, 18);
double withTip(double bill) => addPercent(bill, 10);

void main() {
  print(f(1000, 18));
  print(withGst(1000));
  print(withTip(500));
}

Animated explainer: From idea to finished program

Press Next to walk through it step by step, or Auto play.

Animated explainer: Layers of a clean program

Press Next to walk through it step by step, or Auto play.

Effective Dart: 12 habits of clean code

1. Names

Classes UpperCamelCase, variables and functions lowerCamelCase, files snake_case.

2. Small functions

One function, one job. If it needs "and" in its name, split it.

3. final by default

Use final or const unless the value must change.

4. Types for public code

Write return types on functions so readers know what comes back.

5. Null safety

Avoid ! unless you are certain. Prefer ?? and checks.

6. Comments explain why

Code shows what; comments explain the reason.

7. Interpolation

Use 'Hello $name' instead of joining with +.

8. Collection literals

Write [] and {} instead of List() and Map().

9. Arrow for tiny bodies

Use => for one-expression functions.

10. dart format

Run it before every commit. Same style for everyone.

11. dart analyze

Fix every warning. They are free bug reports.

12. Write tests

A test for each rule keeps the project safe when it grows.

Capstone: six portfolio projects

1. Student Grade Book

Classes, maps, sorting and grade rules. Prints a ranked report card for a class.

2. Shop Billing System

Products, cart, GST, discount and a printed invoice. Uses classes and money maths.

3. Quiz Game Engine

Questions as data, scoring, random order, high score table.

4. Bank Simulator

Accounts, deposit, withdraw, transfer, custom exceptions and transaction log.

5. Library or Fee Manager

Enums, sealed results, DateTime due dates and late fines.

6. JSON Inventory

Save and load stock as JSON, low-stock alerts and a text dashboard.

Rule for every project: clear names, small functions, input validation, error handling and at least five tests.

Plan a project in 6 steps

1. Write the goal

One sentence: "A program that prints the class result and ranks students."

2. List the data

Student: name, roll, marks. Decide which classes and fields you need.

3. List the actions

add student, calculate grade, sort, print report. Each action becomes a function.

4. Build the smallest version

Make the simplest version work first, with fake data.

5. Add rules and errors

Validate marks, handle missing data, write tests.

6. Polish and explain

Format output, write the README, record a short demo.

EASYReal project: games and puzzlesExample 1 of 10

Number guessing game

The secret is fixed here so the output is repeatable; replace it with Random in real use. Loop, compare and give hints.
void main() {
  int secret = 42;
  var guesses = [20, 60, 45, 42];
  int tries = 0;
  for (var g in guesses) {
    tries++;
    if (g == secret) {
      print('Guess $g: Correct in $tries tries!');
      break;
    } else if (g < secret) {
      print('Guess $g: too low');
    } else {
      print('Guess $g: too high');
    }
  }
}
Try it yourself: Change the secret to 77.
Change secret and the guesses.
EASYReal project: weather and science tablesExample 2 of 10

Celsius table

A loop generates a conversion table with neat columns.
void main() {
  print('Celsius   Fahrenheit');
  print('-' * 20);
  for (int c = 0; c <= 40; c += 10) {
    double f = c * 9 / 5 + 32;
    print('${c.toString().padLeft(5)}     ${f.toStringAsFixed(1).padLeft(6)}');
  }
}
Try it yourself: Print the table up to 100 in steps of 25.
Change the loop.
EASYReal project: calculator and billing toolsExample 3 of 10

Calculator with switch

A function with switch chooses the operation. Division by zero is handled safely.
String calc(double a, String op, double b) {
  switch (op) {
    case '+': return '${a + b}';
    case '-': return '${a - b}';
    case '*': return '${a * b}';
    case '/': return b == 0 ? 'Cannot divide by zero' : '${a / b}';
    default: return 'Unknown operator $op';
  }
}

void main() {
  print(calc(12, '+', 8));
  print(calc(12, '*', 8));
  print(calc(12, '/', 0));
  print(calc(12, '%', 8));
}
Try it yourself: Add a power operator.
Use pow from dart:math.
EASYReal project: restaurant and trip expense appsExample 4 of 10

Bill splitter

Total, tip and share per person from three numbers.
void main() {
  double bill = 2450;
  int people = 4;
  double tipPct = 10;
  double tip = bill * tipPct / 100;
  double total = bill + tip;
  print('Bill      : Rs $bill');
  print('Tip $tipPct%  : Rs $tip');
  print('Total     : Rs $total');
  print('Per person: Rs ${(total / people).toStringAsFixed(2)}');
}
Try it yourself: Split among 6 people with 5 percent tip.
Change people and tipPct.
EASYReal project: school attendance reportExample 5 of 10

Attendance percentage

Maps and loops calculate each student percentage and flag low attendance.
void main() {
  var present = {'Asha': 82, 'Rohit': 61, 'Meena': 74, 'Sonu': 90};
  int totalDays = 100;
  present.forEach((name, d) {
    double p = d / totalDays * 100;
    String note = p < 75 ? '  <- below 75%, warn parents' : '';
    print('${name.padRight(6)} ${p.toStringAsFixed(0).padLeft(3)}%$note');
  });
}
Try it yourself: Add two more students.
Add pairs to the map.
MEDIUMReal project: productivity appsExample 6 of 10

To-do list manager

A class holds tasks and commands. A list of simulated commands drives the program.
class Task {
  final String title;
  bool done = false;
  Task(this.title);
}
class TodoList {
  final List<Task> tasks = [];
  void add(String t) => tasks.add(Task(t));
  void complete(int i) {
    if (i < 0 || i >= tasks.length) { print('No task #${i + 1}'); return; }
    tasks[i].done = true;
  }
  void show() {
    for (int i = 0; i < tasks.length; i++) {
      print('${i + 1}. [${tasks[i].done ? 'x' : ' '}] ${tasks[i].title}');
    }
    print('${tasks.where((t) => !t.done).length} pending');
  }
}
void main() {
  var todo = TodoList();
  todo.add('Finish Dart module');
  todo.add('Practice 5 examples');
  todo.add('Push project to GitHub');
  todo.complete(0);
  todo.complete(7);
  todo.show();
}
Try it yourself: Add a remove method.
tasks.removeAt(i)
MEDIUMReal project: quiz and exam appsExample 7 of 10

Quiz game engine

Questions are data (a list of maps); one loop asks, checks and scores. Answers are simulated.
void main() {
  var quiz = [
    {'q': 'Capital of Jharkhand?', 'a': 'Ranchi', 'given': 'Ranchi'},
    {'q': 'Language of Flutter?', 'a': 'Dart', 'given': 'Java'},
    {'q': '7 x 8 = ?', 'a': '56', 'given': '56'},
    {'q': 'Largest planet?', 'a': 'Jupiter', 'given': 'jupiter'},
  ];
  int score = 0;
  for (int i = 0; i < quiz.length; i++) {
    var q = quiz[i];
    bool ok = (q['given'] as String).toLowerCase() == (q['a'] as String).toLowerCase();
    if (ok) score++;
    print('Q${i + 1}. ${q['q']}  ${ok ? 'Correct' : 'Wrong (answer: ${q['a']})'}');
  }
  print('Score: $score / ${quiz.length}  (${score / quiz.length * 100}%)');
}
Try it yourself: Add a fifth question.
Add another map to quiz.
MEDIUMReal project: shop stock appsExample 8 of 10

Inventory saved as JSON

Update stock, flag low items and save the result as JSON text, ready to write to a file.
import 'dart:convert';

void main() {
  var stock = {'Rice': 40, 'Dal': 12, 'Oil': 6, 'Salt': 25};
  var sold = {'Rice': 15, 'Oil': 4, 'Dal': 3};
  sold.forEach((k, v) => stock[k] = stock[k]! - v);
  stock.forEach((k, v) => print('${k.padRight(5)} $v${v < 5 ? '  LOW' : ''}'));
  String json = jsonEncode(stock);
  print(json);
  var back = Map<String, int>.from(jsonDecode(json));
  print(back['Rice']);
}
Try it yourself: Add a restock step.
stock['Oil'] = stock['Oil']! + 20;
HARDReal project: banking and wallet appsExample 9 of 10

Bank simulator

Accounts, a custom exception and a transfer that fails safely. A complete mini system.
class LowFunds implements Exception {
  final double shortBy;
  LowFunds(this.shortBy);
  @override
  String toString() => 'short by Rs $shortBy';
}
class Account {
  final String owner;
  double balance;
  Account(this.owner, this.balance);
  void withdraw(double a) {
    if (a > balance) throw LowFunds(a - balance);
    balance -= a;
  }
  void deposit(double a) => balance += a;
}
void transfer(Account f, Account t, double a) {
  try {
    f.withdraw(a);
    t.deposit(a);
    print('Moved Rs $a: ${f.owner} -> ${t.owner}');
  } on LowFunds catch (e) { print('Failed: $e'); }
}
void main() {
  var a = Account('Asha', 5000), b = Account('Rohit', 800);
  transfer(a, b, 1200);
  transfer(b, a, 9000);
  print('${a.owner}: ${a.balance}');
  print('${b.owner}: ${b.balance}');
}
Try it yourself: Add a daily limit of Rs 10,000.
Throw an exception when the amount is too high.
HARDReal project: school and coaching fee managementExample 10 of 10

Fee manager with enum and dates

Enums for status, DateTime for due dates, a map for totals and a record to unpack: modern Dart in one real mini-app.
enum Status { paid, pending, overdue }
class Fee {
  final String name;
  final double amount;
  final DateTime due;
  final bool paid;
  Fee(this.name, this.amount, this.due, this.paid);
  Status on(DateTime d) => paid ? Status.paid : (d.isAfter(due) ? Status.overdue : Status.pending);
}
void main() {
  var today = DateTime(2026, 12, 1);
  var fees = [
    Fee('Asha', 3000, DateTime(2026, 11, 5), true),
    Fee('Rohit', 3000, DateTime(2026, 11, 5), false),
    Fee('Meena', 3000, DateTime(2026, 12, 10), false),
  ];
  var total = <Status, double>{};
  for (var f in fees) {
    var s = f.on(today);
    total[s] = (total[s] ?? 0) + f.amount;
    int days = today.difference(f.due).inDays;
    print('${f.name.padRight(6)} ${s.name.padRight(8)} ${s == Status.overdue ? 'fine Rs ${days * 10}' : ''}');
  }
  var (paid, pending) = (total[Status.paid], total[Status.pending]);
  print('Collected Rs $paid, pending Rs $pending, overdue Rs ${total[Status.overdue]}');
}
Try it yourself: Add a fourth student who is overdue.
Add a Fee with a past due date.

Quick quiz

3 questions. Click an answer.
Which part of a program should only connect the other parts?
data classeslogic functionsmain()comments
What does refactoring mean?
Adding featuresImproving code without changing what it doesDeleting testsCompiling
Which file explains your project to visitors on GitHub?
pubspec.yamlREADME.mdmain.dartLICENSE
Score: 0 / 3

Recap: what you learned in Module 20

Plan

Goal, data, actions, smallest version, rules, polish.

Structure

Data, logic, report and main kept separate.

Safe code

Validate input; custom exceptions.

Save data

JSON survives restarts.

Clean code

Effective Dart habits, format, analyze, tests.

Share

Git, README and a short demo.

Next: the next part of the course.

Git, README and sharing your work

git init
git add .
git commit -m "Student grade book v1"
git branch -M main
git remote add origin https://github.com/you/grade_book.git
git push -u origin main

# every day:
git status
git add .
git commit -m "Add ranking"
git push

README.md

Project name, what it does, how to run it (dart run), sample output and what you learned.

Screenshots or recordings

A 30-second screen recording of the program running makes your project memorable.

Commit often

Small commits with clear messages show how you work.

Career roadmap after Dart

Flutter developer

Next course: build Android and iPhone apps from one codebase. Strong demand in Ranchi, Patna, Kolkata, Bengaluru and remote.

Backend with Dart

Use shelf or Dart Frog to write APIs. Connect to a database and serve JSON to apps.

Software tester / QA

Your testing skills help with automation roles.

Internships and freelance

Offer small apps for local shops, schools and clinics. Start on Upwork or LinkedIn with your portfolio.

Hackathons and open source

Join college hackathons and fix small issues on GitHub to build your name.

Keep learning

Effective Dart, dartpad.dev, pub.dev and the official Dart codelabs.

Next at BrainBit Infotech: Flutter Course, then Flutter Widgets and Design Course.
Click the name to edit it, then press Ctrl+P to print or save as PDF.
BRAINBIT INFOTECH, RANCHI
Certificate of Completion
This is to certify that
Your Name Here
has successfully completed the
Dart Programming Course
20 modules, 200 practical examples, 6 portfolio projects
Date
🏆
Nandan Kumar, Trainer

Dart Code Lab - write any Dart program (Ctrl+Enter to run)