dart:math, dart:convert, DateTime, RegExp, Uri, Stopwatch and reading input · 7 h
pubspec.yaml, pub.dev, imports, unit tests, debugging and clean code · 6 h
Searching, sorting, recursion, stacks, queues, linked lists and Big-O thinking · 7 h
Put everything together, write clean Dart and plan your next step · 8 h
28 class hours · 40 practice examples · Trainer: Nandan Kumar, Ranchi
Every server reply is JSON. jsonDecode turns it into maps and lists.
DateTime adds days and finds the difference between dates.
RegExp checks phone numbers, emails and PIN codes.
Import with import 'dart:math';. You get sqrt, pow, min, max, pi, sin, cos and 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 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.
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(year, month, day) makes a date. add, subtract, difference and isBefore do date maths. Duration is an amount of time.
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));
}A regular expression describes a pattern. hasMatch tests, firstMatch and allMatches find. Handy: \d digit, + one or more, ^ start, $ end, [a-z] range.
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.parse splits a web address into parts. Stopwatch measures how long code takes.
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);
}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.
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');
}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)}');
}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)}');
}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'));
}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]}');
}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]}');
}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}');
}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')}');
}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));
}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()));
}Asha , 88 , 92import '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}%');
}sqrt, pow, min, max, pi, Random.
jsonEncode to send, jsonDecode to receive.
add, difference, isBefore, weekday.
Validate and extract patterns.
Split links; measure time.
readLineSync reads typed input in console programs.
No code is accepted without tests. Tests catch bugs before customers do.
http, intl, provider and thousands more are one line away.
Clean names, format and analyze keep many developers on one codebase.
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.
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.mdList packages under dependencies. Run dart pub get to download them. Search packages on pub.dev. Use dart pub add http as a shortcut.
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
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.
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';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.)
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 testThe 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.
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');
}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.
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]));
}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');
}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');
}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');
}
}import 'dart:math' as math;
void main() {
print(math.sqrt(144));
print(math.pow(2, 8));
print(math.min(4, 9));
}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}'));
}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);
}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(''));
}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!');
}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');
}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);
}bin, lib, test and pubspec.yaml.
pub.dev, dependencies, dart pub get.
dart:, package: and file imports; as, show, hide.
test, group and expect; dart test.
print, assert, breakpoints, read errors.
Clear names, dart format, dart analyze.
Binary search finds a name in a sorted list of millions in about 20 steps.
A stack remembers the last actions.
Companies test these ideas in every coding round.
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.
Reading list[5]. Always instant.
Binary search: 1,000,000 items need about 20 steps.
Linear search: up to 1,000,000 steps for 1,000,000 items.
Bubble sort on 1,000,000 items is hopeless.
Linear: check items one by one. Works on any list. Binary: needs a sorted list; check the middle, throw away half, repeat.
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));
}Bubble sort compares neighbours and swaps them if they are in the wrong order. Repeat until no swaps. Simple but slow: good for learning.
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: 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.
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 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.
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: last in, first out (plates). Queue: first in, first out (ticket line). Linked list: nodes each pointing to the next one.
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);
}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));
}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]));
}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);
}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}');
}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]));
}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);
}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]));
}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)}');
}
}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));
}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();
}Ask how work grows when data grows.
Linear checks all; binary halves a sorted list.
Bubble, selection, insertion: learn; list.sort() in real code.
Smaller copies of the same problem and a base case.
LIFO, FIFO and linked nodes.
Counting and two-sum in one pass.
Six working projects with a README prove your skill.
You can explain how and why your program is built.
Local shops and schools need small tools. Your projects are the samples.
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.
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])]);
}Never trust data. Check ranges, handle missing items and use custom exceptions so errors have clear names.
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');
}
}
}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.
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}');
}Refactoring means improving code without changing what it does. Rename unclear variables, split long functions, remove repeated code.
// 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));
}Classes UpperCamelCase, variables and functions lowerCamelCase, files snake_case.
One function, one job. If it needs "and" in its name, split it.
Use final or const unless the value must change.
Write return types on functions so readers know what comes back.
Avoid ! unless you are certain. Prefer ?? and checks.
Code shows what; comments explain the reason.
Use 'Hello $name' instead of joining with +.
Write [] and {} instead of List() and Map().
Use => for one-expression functions.
Run it before every commit. Same style for everyone.
Fix every warning. They are free bug reports.
A test for each rule keeps the project safe when it grows.
Classes, maps, sorting and grade rules. Prints a ranked report card for a class.
Products, cart, GST, discount and a printed invoice. Uses classes and money maths.
Questions as data, scoring, random order, high score table.
Accounts, deposit, withdraw, transfer, custom exceptions and transaction log.
Enums, sealed results, DateTime due dates and late fines.
Save and load stock as JSON, low-stock alerts and a text dashboard.
One sentence: "A program that prints the class result and ranks students."
Student: name, roll, marks. Decide which classes and fields you need.
add student, calculate grade, sort, print report. Each action becomes a function.
Make the simplest version work first, with fake data.
Validate marks, handle missing data, write tests.
Format output, write the README, record a short demo.
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');
}
}
}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)}');
}
}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));
}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)}');
}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');
});
}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();
}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}%)');
}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']);
}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}');
}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]}');
}Goal, data, actions, smallest version, rules, polish.
Data, logic, report and main kept separate.
Validate input; custom exceptions.
JSON survives restarts.
Effective Dart habits, format, analyze, tests.
Git, README and a short demo.
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
Project name, what it does, how to run it (dart run), sample output and what you learned.
A 30-second screen recording of the program running makes your project memorable.
Small commits with clear messages show how you work.
Next course: build Android and iPhone apps from one codebase. Strong demand in Ranchi, Patna, Kolkata, Bengaluru and remote.
Use shelf or Dart Frog to write APIs. Connect to a database and serve JSON to apps.
Your testing skills help with automation roles.
Offer small apps for local shops, schools and clinics. Start on Upwork or LinkedIn with your portfolio.
Join college hackathons and fix small issues on GitHub to build your name.
Effective Dart, dartpad.dev, pub.dev and the official Dart codelabs.