DART PROGRAMMING COURSE · BRAINBIT INFOTECH

Part 3
Safe and Object-Oriented Dart

Module 9: Null Safety

Nullable types, ?, ??, ?., !, late and required · 5 h

Module 10: Classes and Objects

Blueprints and real things: fields, methods, constructors, getters, static · 7 h

Module 11: Inheritance, Interfaces and Mixins

Reuse code with extends, override, abstract, implements and with · 7 h

Module 12: Enums, Records and Pattern Matching

Named choices, returning many values, and modern switch and destructuring · 6 h

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

MODULE 9 · PART 3

Null Safety

Nullable types, ?, ??, ?., !, late and required
You will learn
  • What null means and why it causes crashes
  • Nullable (String?) and non-nullable (String) types
  • Null-aware operators: ?. ?? ??= ?[]
  • The ! operator and when not to use it
  • Checking with if and type promotion
  • late variables and required parameters
You will build: a safe profile screen, a form with optional fields and a lookup that never crashes
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🛡

Where is this used in real apps?

Null means "no value here". Using a missing value is the most common reason apps crash. Dart null safety catches many such mistakes before the app runs.

Optional form fields

A user may skip "middle name". The field is nullable.

Lookups

Searching a map or list can find nothing. The result is null.

Safe apps

Fewer crashes means fewer bad reviews.

Profile
👤
Name: Asha
required
📞
Phone: not given
optional (null)
📧
Email: asha@mail.com
required

Nullable and non-nullable

String can never be null. String? (with a question mark) may hold text or null. Dart refuses to let you use a nullable value as if it were sure.

Read it as: String? = "maybe a String".
void main() {
  String name = 'Asha';
  String? middle;
  print(name);
  print(middle);
  middle = 'Kumari';
  print(middle);
  int? age;
  print(age == null);
}

Safe access with ?.

value?.length calls the method only if value is not null; otherwise the answer is null and nothing crashes.

Real use: reading optional data from a server.
void main() {
  String? a = 'Ranchi';
  String? b;
  print(a?.length);
  print(b?.length);
  print(a?.toUpperCase());
  print(b?.toUpperCase());
}

Fallback with ?? and ??=

x ?? fallback gives the fallback when x is null. x ??= value stores the value only when x is null.

Real use: show "Not provided" when a field is empty.
void main() {
  String? nick;
  print(nick ?? 'No nickname');
  nick ??= 'Chotu';
  print(nick);
  nick ??= 'Other';
  print(nick);
  int? score;
  print((score ?? 0) + 10);
}

The ! operator

value! says "I promise this is not null". If you are wrong the program crashes. Use it only when you are really sure; prefer ?? or if-checks.

Rule: every ! is a small bet. Prefer a check.
void main() {
  String? city = 'Patna';
  print(city!.length);
  String? none;
  try {
    print(none!.length);
  } catch (e) {
    print('Crash avoided: value was null');
  }
}

Checking and type promotion

After if (x != null), Dart knows x is not null inside the block (it is "promoted"). No ! needed.

Tip: early return for null keeps the rest of the function clean.
void show(String? text) {
  if (text == null) {
    print('Nothing to show');
    return;
  }
  print('Length: ${text.length}');
}

void main() {
  show('Dart');
  show(null);
  String? x = 'abc';
  if (x != null && x.isNotEmpty) {
    print(x.toUpperCase());
  }
}

late and required

late promises a non-null variable will be set before it is used (and can delay a heavy calculation). required forces callers to give a named parameter.

Real use: required is everywhere in Flutter widgets.
class Course {
  final String title;
  final int fee;
  Course({required this.title, required this.fee});
}

late String greeting;

void main() {
  greeting = 'Namaste';
  print(greeting);
  late int total = 5 * 20;
  print(total);
  var c = Course(title: 'Dart', fee: 3000);
  print('${c.title} Rs ${c.fee}');
}

Animated explainer: Nullable vs non-nullable

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

Animated explainer: Which operator to use?

Press Next to walk through it step by step, or Auto play.
EASYReal project: sign-up formExample 1 of 10

Optional phone

A nullable variable can be empty. Printing shows null.
void main() {
  String name = 'Asha';
  String? phone;
  print('Name : $name');
  print('Phone: $phone');
  phone = '98001 11111';
  print('Phone: $phone');
}
Try it yourself: Add an optional email.
String? email;
EASYReal project: profile screenExample 2 of 10

Default text

?? gives a friendly fallback.
void main() {
  String? bio;
  print(bio ?? 'No bio added yet');
  String? city = 'Ranchi';
  print(city ?? 'City unknown');
}
Try it yourself: Show 'Not given' for a missing age.
int? age; print(age ?? ...);
EASYReal project: text input validationExample 3 of 10

Safe length

?. avoids a crash when text is null.
void main() {
  String? a = 'Hello';
  String? b;
  print(a?.length);
  print(b?.length);
  print(b?.length ?? 0);
}
Try it yourself: Use ?.toUpperCase() on both.
a?.toUpperCase()
EASYReal project: checking before usingExample 4 of 10

Null check

A plain if check is the clearest way to be safe.
void main() {
  String? token;
  if (token == null) {
    print('Please log in');
  } else {
    print('Token is $token');
  }
  token = 'abc123';
  print(token == null ? 'No token' : 'Token ready');
}
Try it yourself: Check a nullable score.
int? score;
EASYReal project: caching a value onceExample 5 of 10

Assign if null

??= sets a value only the first time.
void main() {
  String? theme;
  theme ??= 'light';
  print(theme);
  theme ??= 'dark';
  print(theme);
}
Try it yourself: Use ??= for a language setting.
String? lang; lang ??= 'Hindi';
MEDIUMReal project: finding a user in a mapExample 6 of 10

Safe lookup

A map returns null for missing keys. ?? and ?. make the code safe.
void main() {
  var emails = {'asha': 'asha@mail.com', 'rohit': 'rohit@mail.com'};
  for (var u in ['asha', 'zoya', 'rohit']) {
    String? e = emails[u];
    print('$u -> ${e ?? 'not registered'}');
  }
  print(emails['zoya']?.toUpperCase());
}
Try it yourself: Add a user with no email.
Search for a name that is not in the map.
MEDIUMReal project: sign-up formExample 7 of 10

Form validator

A function returns an error message (String?) or null if the data is good. This pattern is used by Flutter forms.
String? validateName(String? v) {
  if (v == null || v.trim().isEmpty) return 'Name is required';
  if (v.length < 3) return 'Name is too short';
  return null;
}

void main() {
  for (String? t in [null, '  ', 'Al', 'Asha']) {
    print('"${t ?? 'null'}" -> ${validateName(t) ?? 'OK'}');
  }
}
Try it yourself: Write validateAge for ages 5 to 100.
Return a message or null.
MEDIUMReal project: building cards and widgetsExample 8 of 10

Optional named parameters

Named parameters can be nullable or have defaults. Callers skip what they do not need.
String describe({required String name, String? city, int age = 18}) {
  String where = city ?? 'unknown city';
  return '$name, $age, from $where';
}

void main() {
  print(describe(name: 'Asha'));
  print(describe(name: 'Rohit', city: 'Patna'));
  print(describe(name: 'Meena', age: 21, city: 'Gaya'));
}
Try it yourself: Add an optional phone parameter.
String? phone
HARDReal project: reading JSON from a serverExample 9 of 10

Optional chain of data

Real data can miss any level. Chain ?. and ?? so nothing crashes.
void main() {
  Map<String, dynamic> response = {
    'user': {'name': 'Asha', 'address': {'city': 'Ranchi'}},
  };
  Map<String, dynamic> response2 = {'user': {'name': 'Rohit'}};
  for (var r in [response, response2, <String, dynamic>{}]) {
    var city = r['user']?['address']?['city'] ?? 'City not available';
    var name = r['user']?['name'] ?? 'Guest';
    print('$name lives in $city');
  }
}
Try it yourself: Add a response with only an address.
Make a new map.
HARDReal project: reporting with missing marksExample 10 of 10

Safe student report

Marks can be missing (null). The report treats missing as absent and still computes totals safely.
void main() {
  Map<String, int?> marks = {'Maths': 78, 'Science': null, 'English': 66};
  int total = 0;
  int taken = 0;
  marks.forEach((sub, m) {
    if (m == null) {
      print('${sub.padRight(8)} absent');
      return;
    }
    print('${sub.padRight(8)} $m');
    total += m;
    taken++;
  });
  print('Exams taken: $taken');
  print('Total: $total, Average: ${taken == 0 ? 0 : (total / taken).toStringAsFixed(1)}');
}
Try it yourself: Make English absent too.
Set English to null.

Quick quiz

3 questions. Click an answer.
What does String? mean?
A very long stringA string that may be nullA required stringA final string
What does name ?? 'Guest' do?
Always returns GuestReturns name, or Guest if name is nullCrashes on nullConverts to uppercase
What happens if you use ! on a null value?
Returns 0Returns an empty stringThe program throws an errorNothing
Score: 0 / 3

Recap: what you learned in Module 9

Null

Means no value. Using it blindly crashes apps.

Types

String can never be null; String? may be.

?. and ??

Safe call and fallback value.

!

A promise. Wrong promise means a crash.

Checks

if (x != null) lets Dart promote the type.

late / required

Set before use / must be provided.

Next: Classes and Objects - Blueprints and real things: fields, methods, constructors, getters, static
MODULE 10 · PART 3

Classes and Objects

Blueprints and real things: fields, methods, constructors, getters, static
You will learn
  • What a class and an object are
  • Fields (data) and methods (actions)
  • Constructors, named constructors and this
  • Private members with _ and getters/setters
  • static members, toString and const constructors
  • Lists of objects and object relationships
You will build: a Student class, a BankAccount and a Product catalogue
7 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🏗

Where is this used in real apps?

A class is a blueprint, like the plan of a house. An object is a real house built from it. Apps model real things (student, product, account) as classes.

School software

Each student is an object made from the Student class.

Banking

BankAccount has a balance and methods deposit() and withdraw().

Flutter

Every widget is an object. You will write many classes.

Students
🎓
Asha - Class 8
Student object
🎓
Rohit - Class 9
Student object
🎓
Meena - Class 8
Student object

Class and object

A class lists the fields (what it knows) and methods (what it can do). Student() builds an object. Use a dot to reach inside.

Two objects from one class each keep their own data.
class Student {
  String name = '';
  int marks = 0;

  void show() {
    print('$name scored $marks');
  }
}

void main() {
  var a = Student();
  a.name = 'Asha';
  a.marks = 91;
  var b = Student();
  b.name = 'Rohit';
  b.marks = 67;
  a.show();
  b.show();
}

Constructors

A constructor fills the fields when the object is made. this.name in the brackets is a shortcut that copies the argument into the field. Named constructors give extra ways to build.

Flutter style: Text('Hi') calls the Text constructor.
class Student {
  String name;
  int marks;

  Student(this.name, this.marks);
  Student.newJoiner(this.name) : marks = 0;

  void show() => print('$name: $marks');
}

void main() {
  Student('Asha', 91).show();
  Student.newJoiner('Kiran').show();
}

Methods that change data

Methods can read and change the fields of the object they belong to. Inside a method, fields are used by name.

Real use: the rules (no overdraft) live inside the class.
class Account {
  String owner;
  double balance;
  Account(this.owner, this.balance);
  void deposit(double amount) {
    balance += amount;
  }
  bool withdraw(double amount) {
    if (amount > balance) return false;
    balance -= amount;
    return true;
  }
}
void main() {
  var acc = Account('Asha', 1000);
  acc.deposit(500);
  print(acc.withdraw(2000));
  print(acc.withdraw(300));
  print(acc.balance);
}

Private fields and getters

A name starting with _ is private to its file. Provide a getter to read it and a setter or method to change it safely.

Why: the class protects its own data from wrong values.
class Temp {
  double _celsius = 0;
  double get celsius => _celsius;
  double get fahrenheit => _celsius * 9 / 5 + 32;
  set celsius(double v) {
    if (v < -273.15) {
      print('Impossible temperature');
      return;
    }
    _celsius = v;
  }
}
void main() {
  var t = Temp();
  t.celsius = 36.5;
  print(t.fahrenheit);
  t.celsius = -500;
  print(t.celsius);
}

static, toString, const

static belongs to the class itself, not to an object. toString() controls how an object prints. const constructors make fixed objects.

Real use: a counter shared by all objects, such as the next invoice number.
class School {
  static int count = 0;
  static const String name = 'BrainBit Infotech Academy';
  final String student;
  School(this.student) {
    count++;
  }

  @override
  String toString() => '$student @ $name';
}

void main() {
  var a = School('Asha');
  var b = School('Rohit');
  print(a);
  print(School.count);
  print(b);
}

Lists of objects

Real programs keep many objects in a list, then loop, filter and sort them.

Next: inheritance lets Product share features with other classes.
class Product {
  final String name;
  final double price;
  Product(this.name, this.price);
}

void main() {
  var items = [Product('Pen', 10), Product('Book', 150), Product('Bag', 700)];
  for (var p in items) {
    print('${p.name}: Rs ${p.price}');
  }
  var costly = items.where((p) => p.price > 100).map((p) => p.name);
  print(costly.toList());
  print(items.fold(0.0, (s, p) => s + p.price));
}

Animated explainer: Class = blueprint, Object = thing

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

Animated explainer: Deposit and withdraw

Press Next to walk through it step by step, or Auto play.
EASYReal project: school softwareExample 1 of 10

Student class

A class with two fields and a method. Each object keeps its own values.
class Student {
  String name;
  int marks;
  Student(this.name, this.marks);

  void show() {
    print('$name scored $marks');
  }
}

void main() {
  Student('Asha', 91).show();
  Student('Rohit', 67).show();
}
Try it yourself: Add a city field.
Add String city; and change the constructor.
EASYReal project: floor and plot area toolsExample 2 of 10

Rectangle

A method uses the fields of its own object.
class Rectangle {
  double length, breadth;
  Rectangle(this.length, this.breadth);

  double area() => length * breadth;
  double perimeter() => 2 * (length + breadth);
}

void main() {
  var r = Rectangle(12, 8);
  print('Area      : ${r.area()}');
  print('Perimeter : ${r.perimeter()}');
}
Try it yourself: Add a method isSquare().
return length == breadth;
EASYReal project: library appExample 3 of 10

Book card

A class groups related data and gives it one name.
class Book {
  final String title;
  final String author;
  final int pages;
  Book(this.title, this.author, this.pages);

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

void main() {
  print(Book('Godan', 'Premchand', 336));
  print(Book('Wings of Fire', 'A. P. J. Abdul Kalam', 180));
}
Try it yourself: Add your favourite book.
Make a new Book(...).
EASYReal project: visitor counter or like buttonExample 4 of 10

Counter

A method changes the object state.
class Counter {
  int value = 0;
  void increment() => value++;
  void reset() => value = 0;
}

void main() {
  var c = Counter();
  c.increment();
  c.increment();
  c.increment();
  print(c.value);
  c.reset();
  print(c.value);
}
Try it yourself: Add a decrement method.
void decrement() => value--;
EASYReal project: creating objects in different waysExample 5 of 10

Named constructor

A named constructor builds an object from special input such as one value.
class Point {
  final double x, y;
  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
  Point.same(double v) : x = v, y = v;

  @override
  String toString() => '($x, $y)';
}

void main() {
  print(Point(3, 4));
  print(Point.origin());
  print(Point.same(5));
}
Try it yourself: Add Point.onXAxis(double x).
: x = x, y = 0
MEDIUMReal project: banking appExample 6 of 10

Bank account

Rules live inside the class: no overdraft, no negative deposits.
class Account {
  final String owner;
  double _balance = 0;
  Account(this.owner, [double opening = 0]) {
    _balance = opening;
  }
  double get balance => _balance;
  bool deposit(double amt) {
    if (amt <= 0) return false;
    _balance += amt;
    return true;
  }
  bool withdraw(double amt) {
    if (amt <= 0 || amt > _balance) return false;
    _balance -= amt;
    return true;
  }
}
void main() {
  var a = Account('Asha', 2000);
  print(a.deposit(500));
  print(a.withdraw(5000));
  print(a.withdraw(700));
  print('Balance: Rs ${a.balance}');
}
Try it yourself: Add a method that adds 4 percent interest.
_balance *= 1.04;
MEDIUMReal project: e-commerce back endExample 7 of 10

Product catalogue

A list of objects: filter, sort and total them.
class Product {
  final String name;
  final double price;
  final int stock;
  Product(this.name, this.price, this.stock);
  double get value => price * stock;
}

void main() {
  var items = [Product('Pen', 10, 200), Product('Book', 150, 40), Product('Bag', 700, 5)];
  items.sort((a, b) => b.value.compareTo(a.value));
  for (var p in items) {
    print('${p.name.padRight(5)} ${p.stock.toString().padLeft(4)} x ${p.price} = ${p.value}');
  }
  print('Stock value: ${items.fold(0.0, (s, p) => s + p.value)}');
}
Try it yourself: Add a low-stock list (stock < 10).
items.where((p) => p.stock < 10)
MEDIUMReal project: IoT sensor appExample 8 of 10

Temperature with setter

A setter validates data before storing it.
class Sensor {
  double _c = 25;
  double get celsius => _c;
  double get fahrenheit => _c * 9 / 5 + 32;
  set celsius(double v) {
    if (v < -50 || v > 150) {
      print('Rejected $v');
      return;
    }
    _c = v;
  }
}

void main() {
  var s = Sensor();
  s.celsius = 40;
  print('${s.celsius} C = ${s.fahrenheit} F');
  s.celsius = 900;
  print(s.celsius);
}
Try it yourself: Reject below -20.
Change the lower limit.
HARDReal project: library management softwareExample 9 of 10

Library system

Two classes work together: a Library holds many Books and lends them. This is how real systems are modelled.
class Book {
  final String title;
  bool lent = false;
  Book(this.title);
}
class Library {
  final List<Book> books = [];
  void add(String t) => books.add(Book(t));
  String lend(String t) {
    for (var b in books) {
      if (b.title != t) continue;
      if (b.lent) return '$t is already lent';
      b.lent = true;
      return 'Lent: $t';
    }
    return '$t not found';
  }
}
void main() {
  var lib = Library();
  lib.add('Godan');
  print(lib.lend('Godan'));
  print(lib.lend('Godan'));
  print(lib.lend('Ramayan'));
}
Try it yourself: Add a return method.
Find the book and set lent = false.
HARDReal project: e-commerce checkoutExample 10 of 10

Shopping cart with GST

Cart holds items; every item knows its price; the cart computes totals. Real checkout logic.
class Item {
  final String name;
  final double price;
  final int qty;
  Item(this.name, this.price, this.qty);
  double get total => price * qty;
}
class Cart {
  final List<Item> items = [];
  void add(Item i) => items.add(i);
  double get subtotal => items.fold(0.0, (s, i) => s + i.total);
  double get tax => subtotal * 0.18;
}
void main() {
  var c = Cart();
  c.add(Item('Notebook', 60, 5));
  c.add(Item('Pen', 10, 10));
  c.add(Item('Bag', 799, 1));
  for (var i in c.items) {
    print('${i.name.padRight(8)} ${i.qty} x ${i.price} = ${i.total}');
  }
  print('Subtotal : ${c.subtotal}');
  print('GST 18%  : ${c.tax.toStringAsFixed(2)}');
  print('Payable  : ${(c.subtotal + c.tax).toStringAsFixed(2)}');
}
Try it yourself: Add a discount percent field to Cart.
Subtract a discount from subtotal.

Quick quiz

3 questions. Click an answer.
What is an object?
A blueprintA real thing made from a classA functionA loop
What does a name starting with _ mean?
ConstantPrivate to the fileStaticNullable
Which keyword refers to the current object inside a constructor?
selfmethisobject
Score: 0 / 3

Recap: what you learned in Module 10

Class

Blueprint with fields and methods.

Object

A real instance made with ClassName(...).

Constructor

Fills fields; this.x shortcut; named constructors.

Private

_name hides data; getters and setters control access.

static

Belongs to the class, shared by all objects.

Lists of objects

Loop, filter, sort and total real data.

Next: Inheritance, Interfaces and Mixins - Reuse code with extends, override, abstract, implements and with
MODULE 11 · PART 3

Inheritance, Interfaces and Mixins

Reuse code with extends, override, abstract, implements and with
You will learn
  • Inheritance with extends and super
  • Overriding methods and polymorphism
  • Abstract classes: a contract to fill
  • Interfaces with implements
  • Mixins with with: share features
  • is, as and choosing between the tools
You will build: a payment system, a school staff hierarchy and a shape calculator
7 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🧬

Where is this used in real apps?

Many things share features. A Teacher and a Student are both Persons. Inheritance lets a new class reuse an old one, so you write common code only once.

Payment apps

UPI, Card and NetBanking are all Payment types with a pay() method.

Flutter

Every widget extends StatelessWidget or StatefulWidget.

School software

Teacher and Student extend Person.

Pay Now
💳
Card payment
extends Payment
📱
UPI payment
extends Payment
🏦
NetBanking
extends Payment

extends and super

class Teacher extends Person gets everything Person has. super reaches the parent class, for example to pass values to its constructor.

Is-a rule: use extends only when "Teacher is a Person" sounds correct.
class Person {
  String name;
  Person(this.name);
  void intro() => print('I am $name');
}

class Teacher extends Person {
  String subject;
  Teacher(String name, this.subject) : super(name);
  void teach() => print('$name teaches $subject');
}

void main() {
  var t = Teacher('Mr Sinha', 'Maths');
  t.intro();
  t.teach();
}

Override and polymorphism

A child class can change a method with @override. A list of parent type can hold different children; each answers in its own way. That is polymorphism.

Real use: for (p in payments) p.pay(): one call, many behaviours.
class Animal {
  void sound() => print('Some sound');
}
class Dog extends Animal {
  @override
  void sound() => print('Woof');
}
class Cat extends Animal {
  @override
  void sound() {
    print('Meow');
  }
}
void main() {
  List<Animal> zoo = [Dog(), Cat(), Animal()];
  for (var a in zoo) {
    a.sound();
  }
}

Abstract classes

An abstract class cannot be built itself. It lists methods that children must write. It is a contract: "every shape must be able to give an area".

Trying Shape() is an error, because Shape is incomplete by design.
abstract class Shape {
  double area();
  void describe() => print('Area is ${area()}');
}
class Square extends Shape {
  double side;
  Square(this.side);
  @override
  double area() => side * side;
}
class Circle extends Shape {
  double r;
  Circle(this.r);
  @override double area() => 3.14 * r * r;
}
void main() {
  Square(4).describe();
  Circle(2).describe();
}

Interfaces with implements

Every class is also an interface. implements says "I promise to provide all these members" without inheriting any code. A class can implement many interfaces.

extends = one parent, reuse code. implements = many promises, no code reused.
abstract class Printable {
  void printMe();
}
abstract class Savable {
  void save();
}
class Report implements Printable, Savable {
  @override
  void printMe() => print('Printing report');
  @override
  void save() => print('Saving report');
}
void main() {
  var r = Report();
  r.printMe();
  r.save();
  print(r is Printable);
}

Mixins

A mixin is a bundle of features that you can add to any class with with. It is how unrelated classes share a feature, like logging.

Real use: logging, timestamps and validation shared by many classes.
mixin Logger {
  void log(String m) => print('[LOG] $m');
}
mixin Walker {
  void walk() => print('Walking');
}

class Robot with Logger, Walker {
  String name;
  Robot(this.name);
}

void main() {
  var r = Robot('R2');
  r.log('Started ${r.name}');
  r.walk();
}

is, as and choosing

is tests a type. as converts. After an is check Dart treats the object as that type.

Choose: extends to specialise, abstract for a contract with shared code, implements for a pure promise, mixin to add an ability.
class Animal {}
class Dog extends Animal {
  void bark() => print('Woof!');
}

void main() {
  Animal a = Dog();
  print(a is Dog);
  print(a is Animal);
  if (a is Dog) {
    a.bark();
  }
  Dog d = a as Dog;
  d.bark();
}

Animated explainer: Inheritance tree

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

Animated explainer: Polymorphism: one call, many answers

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

Parent and child

The child gets the parent features without rewriting them.
class Person {
  String name;
  Person(this.name);
  void intro() => print('Hello, I am $name');
}

class Student extends Person {
  int roll;
  Student(String name, this.roll) : super(name);
}

void main() {
  var s = Student('Asha', 12);
  s.intro();
  print('Roll ${s.roll}');
}
Try it yourself: Add a Teacher class.
class Teacher extends Person {...}
EASYReal project: customising behaviourExample 2 of 10

Override a method

@override replaces the parent behaviour in the child.
class Vehicle {
  void start() => print('Vehicle starting');
}
class Bike extends Vehicle {
  @override
  void start() => print('Kick start the bike');
}
class Car extends Vehicle {
  @override
  void start() => print('Press the start button');
}

void main() {
  Vehicle().start();
  Bike().start();
  Car().start();
}
Try it yourself: Add a Truck class.
extends Vehicle and override start().
EASYReal project: extending behaviour without losing the old oneExample 3 of 10

Calling super

super.method() runs the parent code first; then the child adds more.
class Notification {
  void send() => print('Sending notification');
}
class SmsNotification extends Notification {
  @override
  void send() {
    super.send();
    print('...via SMS');
  }
}

void main() {
  SmsNotification().send();
}
Try it yourself: Add an EmailNotification.
Copy SmsNotification and edit.
EASYReal project: drawing and CAD appsExample 4 of 10

Abstract shapes

The abstract class forces every shape to provide area().
abstract class Shape {
  String name;
  Shape(this.name);
  double area();
  void show() => print('$name area = ${area()}');
}
class Rect extends Shape {
  double w, h;
  Rect(this.w, this.h) : super('Rectangle');
  @override
  double area() => w * h;
}
class Tri extends Shape {
  double b, h;
  Tri(this.b, this.h) : super('Triangle');
  @override
  double area() => 0.5 * b * h;
}
void main() {
  Rect(4, 5).show();
  Tri(6, 3).show();
}
Try it yourself: Add a Circle shape.
area => 3.14 * r * r
EASYReal project: sharing a feature across classesExample 5 of 10

Simple mixin

A mixin adds the log method to any class.
mixin Logger {
  void log(String m) => print('[LOG] $m');
}
class Shop with Logger {
  void sell() => log('Item sold');
}
class School with Logger {
  void admit() => log('Student admitted');
}

void main() {
  Shop().sell();
  School().admit();
}
Try it yourself: Add a Hospital class using the mixin.
class Hospital with Logger {...}
MEDIUMReal project: payment gatewayExample 6 of 10

Payment system

One list of Payment objects, each paying in its own way. Add a new type and the loop code stays the same.
abstract class Payment {
  double amount;
  Payment(this.amount);
  void pay();
}
class CardPayment extends Payment {
  CardPayment(double a) : super(a);
  @override
  void pay() => print('Card charged Rs $amount (+2% fee = ${amount * 1.02})');
}
class UpiPayment extends Payment {
  UpiPayment(double a) : super(a);
  @override
  void pay() => print('UPI payment of Rs $amount done');
}
class CashPayment extends Payment {
  CashPayment(double a) : super(a);
  @override
  void pay() => print('Collected Rs $amount in cash');
}
void main() {
  List<Payment> bills = [CardPayment(1000), UpiPayment(450), CashPayment(200)];
  for (var b in bills) {
    b.pay();
  }
}
Try it yourself: Add a WalletPayment class.
class WalletPayment extends Payment
MEDIUMReal project: school ERPExample 7 of 10

School staff

Salary rules differ per role, but payroll code treats all as Staff.
abstract class Staff {
  String name;
  Staff(this.name);
  double salary();
}
class Teacher extends Staff {
  int periods;
  Teacher(String n, this.periods) : super(n);
  @override
  double salary() => 20000 + periods * 300;
}
class Clerk extends Staff {
  Clerk(String n) : super(n);
  @override double salary() => 18000;
}
class Principal extends Staff {
  Principal(String n) : super(n);
  @override double salary() => 55000;
}
void main() {
  var staff = <Staff>[Teacher('Mr Sinha', 24), Clerk('Mrs Devi'), Principal('Dr Rao')];
  double total = 0;
  for (var s in staff) {
    print('${s.name.padRight(9)} Rs ${s.salary()}');
    total += s.salary();
  }
  print('Payroll   Rs $total');
}
Try it yourself: Add a Peon with Rs 12,000.
class Peon extends Staff
MEDIUMReal project: apps that accept add-onsExample 8 of 10

Interfaces for plugins

Different classes promise the same methods, so the app can use them interchangeably.
abstract class Notifier {
  void notify(String msg);
}
class Sms implements Notifier {
  @override
  void notify(String msg) => print('SMS: $msg');
}
class Email implements Notifier {
  @override
  void notify(String msg) => print('Email: $msg');
}
class Push implements Notifier {
  @override
  void notify(String msg) => print('Push: $msg');
}
void alertAll(List<Notifier> channels, String m) {
  for (var c in channels) {
    c.notify(m);
  }
}
void main() {
  alertAll([Sms(), Email(), Push()], 'Fees due on 5th');
}
Try it yourself: Add a WhatsApp channel.
class WhatsApp implements Notifier
HARDReal project: game characters and robotsExample 9 of 10

Mixins for abilities

Abilities are mixed into any class, in any combination. Inheritance alone cannot do this.
mixin CanFly {
  void fly() => print('$runtimeType is flying');
}
mixin CanSwim {
  void swim() => print('$runtimeType is swimming');
}
mixin CanRun {
  void run() => print('$runtimeType is running');
}
class Duck with CanFly, CanSwim, CanRun {}
class Fish with CanSwim {}
class Eagle with CanFly, CanRun {}
void main() {
  var d = Duck();
  d.fly();
  d.swim();
  d.run();
  Fish().swim();
  Eagle().fly();
  print(d is CanSwim);
  print(Fish() is CanFly);
}
Try it yourself: Create a Bat with CanFly only.
class Bat with CanFly {}
HARDReal project: library or media appExample 10 of 10

Library with abstract base and mixin

Abstract base, children, an interface and a mixin together: the full toolbox in one program.
mixin Priced {
  double basePrice = 0;
  double get priceWithGst => basePrice * 1.12;
}
abstract class Item {
  String title;
  Item(this.title);
  String describe();
}
class Book extends Item with Priced {
  int pages;
  Book(String t, this.pages, double p) : super(t) { basePrice = p; }
  @override
  String describe() => 'Book "$title", $pages pages, Rs ${priceWithGst.toStringAsFixed(2)}';
}
class Dvd extends Item with Priced {
  int minutes;
  Dvd(String t, this.minutes, double p) : super(t) { basePrice = p; }
  @override
  String describe() => 'DVD "$title", $minutes min, Rs ${priceWithGst.toStringAsFixed(2)}';
}
void main() {
  List<Item> shelf = [Book('Godan', 336, 250), Dvd('Lagaan', 224, 150)];
  for (var i in shelf) {
    print(i.describe());
  }
}
Try it yourself: Add a Magazine class.
class Magazine extends Item with Priced

Quick quiz

3 questions. Click an answer.
Which keyword makes a child class reuse a parent class?
implementsextendswithimport
What must a class do when it implements an interface?
NothingProvide all its membersExtend it tooBe abstract
What can an abstract class NOT do?
Have methodsBe built directlyBe extendedHave fields
Score: 0 / 3

Recap: what you learned in Module 11

extends

Child reuses parent code; super reaches the parent.

@override

Child replaces a parent method. Polymorphism.

abstract

A contract class that cannot be built directly.

implements

Promise to provide all members, no code reused.

mixin / with

Add shared abilities to any class.

is / as

Test and convert types.

Next: Enums, Records and Pattern Matching - Named choices, returning many values, and modern switch and destructuring
MODULE 12 · PART 3

Enums, Records and Pattern Matching

Named choices, returning many values, and modern switch and destructuring
You will learn
  • enum: a fixed set of named choices
  • Enhanced enums with fields and methods
  • Records: bundle several values without a class
  • Destructuring: unpack lists, maps and records
  • switch expressions and patterns
  • Sealed classes and exhaustive switch
You will build: an order-status tracker, a min/max function and a smart switch for payments
6 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🧩

Where is this used in real apps?

Some data has only a few allowed values: order status (placed, shipped, delivered), days of the week. Enums name them safely. Records and patterns are modern Dart tools that make code shorter and clearer.

Order tracking

Status is an enum: placed, packed, shipped, delivered.

Functions returning two values

A record returns (min, max) together.

Flutter state

loading, success and error are modelled as enum or sealed classes.

Order #1042
📦
Placed
done
🚚
Shipped
now
🏡
Delivered
pending

enum

An enum lists all allowed values. Typing mistakes become impossible: Status.shiped is an error, while the string 'shiped' would silently be wrong.

Real use: days, roles (admin, user), payment modes.
enum Status { placed, shipped, delivered }

void main() {
  Status s = Status.shipped;
  print(s);
  print(s.name);
  print(s.index);
  print(Status.values);
  for (var x in Status.values) {
    print('${x.index}: ${x.name}');
  }
}

Enhanced enums

Enums can carry data and methods. Each value is made with the constructor.

Real use: subscription plans with price and description.
enum Plan {
  free(0, 'Basic'),
  pro(499, 'Advanced'),
  team(1499, 'All features');

  final int price;
  final String label;
  const Plan(this.price, this.label);

  String get info => '$name: Rs $price ($label)';
}

void main() {
  for (var p in Plan.values) {
    print(p.info);
  }
}

Records

A record groups values in round brackets without making a class: (int, int). Great when a function must return two things. Fields: $1, $2, or names.

Think: a record is a small anonymous bundle; use a class when it gets bigger.
(int, int) minMax(List<int> a) {
  var s = [...a]..sort();
  return (s.first, s.last);
}

void main() {
  var r = minMax([40, 7, 93, 18]);
  print(r);
  print(r.$1);
  print(r.$2);
  var person = (name: 'Asha', age: 16);
  print(person.name);
  print(person);
}

Destructuring

Unpack values into variables in one line. Works with records, lists and maps.

Bonus: (a, b) = (b, a) swaps two variables with no helper.
void main() {
  var (a, b) = (10, 20);
  print('$a $b');
  (a, b) = (b, a);
  print('$a $b');
  var [first, second, ...rest] = [1, 2, 3, 4, 5];
  print('$first $second $rest');
  var {'name': n, 'age': g} = {'name': 'Rohit', 'age': 17};
  print('$n $g');
}

switch expressions and patterns

A switch expression returns a value: var x = switch (v) { pattern => result, ... };. Patterns can compare values, ranges and types, and add a when guard.

_ means "anything else".
String grade(int m) => switch (m) {
  >= 90 => 'A+',
  >= 75 => 'A',
  >= 60 => 'B',
  >= 33 => 'C',
  _ => 'Fail',
};
String day(int d) => switch (d) {
  6 || 7 => 'Weekend',
  _ => 'Weekday',
};
void main() {
  print(grade(95));
  print(grade(40));
  print(day(7));
  print(day(2));
  Object o = 42;
  var t = switch (o) { int n when n > 10 => 'big int', int() => 'int', String() => 'text', _ => 'other' };
  print(t);
}

Sealed classes

A sealed class has a fixed family of children. A switch over it must handle every child, or Dart refuses to compile. Perfect for results like loading, success and error.

Real use: every Flutter screen shows loading, data or error. The switch cannot forget one.
sealed class Result {}
class Success extends Result {
  final String data;
  Success(this.data);
}
class Failure extends Result {
  final String error;
  Failure(this.error);
}

String show(Result r) => switch (r) {
  Success(data: var d) => 'Got $d',
  Failure(error: var e) => 'Problem: $e',
};

void main() {
  print(show(Success('Course list')));
  print(show(Failure('No internet')));
}

Animated explainer: Order status flow

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

Animated explainer: A record travels together

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

Days with enum

An enum makes a fixed list of names safe.
enum Day { mon, tue, wed, thu, fri, sat, sun }

void main() {
  Day today = Day.sat;
  print(today.name);
  print(today == Day.sat);
  print('Position: ${today.index}');
  print(Day.values.length);
}
Try it yourself: Check if today is a weekend.
today == Day.sat || today == Day.sun
EASYReal project: e-commerce trackingExample 2 of 10

Order status switch

A switch on an enum picks the message for each status.
enum Status { placed, shipped, delivered }

String message(Status s) {
  switch (s) {
    case Status.placed: return 'We got your order';
    case Status.shipped: return 'On the way to Ranchi';
    case Status.delivered: return 'Delivered. Enjoy!';
  }
}

void main() {
  for (var s in Status.values) {
    print('${s.name}: ${message(s)}');
  }
}
Try it yourself: Add a cancelled status.
Add it to the enum and the switch.
EASYReal project: sorting and algorithmsExample 3 of 10

Swap with destructuring

One line swaps two variables.
void main() {
  int a = 5, b = 9;
  print('Before: $a $b');
  (a, b) = (b, a);
  print('After : $a $b');
}
Try it yourself: Swap two names.
String x, y.
EASYReal project: returning more than one valueExample 4 of 10

Record of two values

A function returns two results as one record.
(int, int) divide(int a, int b) => (a ~/ b, a % b);

void main() {
  var r = divide(17, 5);
  print('Quotient  ${r.$1}');
  print('Remainder ${r.$2}');
  var (q, rem) = divide(100, 7);
  print('$q and $rem');
}
Try it yourself: Return (sum, product) of two numbers.
=> (a + b, a * b)
EASYReal project: result processingExample 5 of 10

Switch expression grade

A switch expression returns the answer directly.
String grade(int m) => switch (m) {
  >= 90 => 'A+',
  >= 75 => 'A',
  >= 60 => 'B',
  >= 33 => 'C',
  _ => 'Fail',
};

void main() {
  for (var m in [95, 80, 61, 40, 12]) {
    print('$m -> ${grade(m)}');
  }
}
Try it yourself: Add a D grade for 33 to 44.
Add a pattern and result.
MEDIUMReal project: pricing page of a SaaS productExample 6 of 10

Subscription plans

Enhanced enum carries data and a method; loops over values build the pricing table.
enum Plan {
  free(0, 1),
  pro(499, 10),
  team(1499, 50);

  final int price;
  final int users;
  const Plan(this.price, this.users);

  double get perUser => users == 0 ? 0 : price / users;
}

void main() {
  for (var p in Plan.values) {
    print('${p.name.padRight(5)} Rs ${p.price.toString().padLeft(5)}  users ${p.users}  per user ${p.perUser.toStringAsFixed(1)}');
  }
}
Try it yourself: Add an enterprise plan.
enterprise(4999, 200)
MEDIUMReal project: analytics dashboardsExample 7 of 10

Statistics record

A function returns a named record with several results.
({int min, int max, double avg}) stats(List<int> v) {
  var s = [...v]..sort();
  double avg = v.fold(0, (a, b) => a + b) / v.length;
  return (min: s.first, max: s.last, avg: avg);
}

void main() {
  var r = stats([72, 85, 91, 64, 78]);
  print('Lowest  ${r.min}');
  print('Highest ${r.max}');
  print('Average ${r.avg}');
  print(r);
}
Try it yourself: Add a count field.
(min:..., max:..., avg:..., count: v.length)
MEDIUMReal project: reading rows and JSONExample 8 of 10

Destructure data

Unpack lists and maps in a single line.
void main() {
  var row = ['Asha', 'Ranchi', 16];
  var [name, city, age] = row;
  print('$name from $city, age $age');
  var info = {'course': 'Dart', 'fee': 3000};
  var {'course': c, 'fee': f} = info;
  print('$c costs Rs $f');
  for (var (x, y) in [(1, 2), (3, 4)]) {
    print('x=$x y=$y');
  }
}
Try it yourself: Destructure a list of 4 values.
var [a, b, c, d] = ...
HARDReal project: API result in Flutter appsExample 9 of 10

Sealed result handling

A sealed family plus a switch expression: the compiler guarantees all cases are handled.
sealed class Result {}
class Loading extends Result {}
class Data extends Result {
  final List<String> items;
  Data(this.items);
}
class Failed extends Result {
  final String why;
  Failed(this.why);
}
String screen(Result r) => switch (r) {
  Loading() => 'Show spinner',
  Data(items: var i) when i.isEmpty => 'Show "no courses yet"',
  Data(items: var i) => 'Show ${i.length} courses: ${i.join(', ')}',
  Failed(why: var w) => 'Show error: $w',
};
void main() {
  for (Result r in [Loading(), Data([]), Data(['Dart', 'Flutter']), Failed('Timeout')]) {
    print(screen(r));
  }
}
Try it yourself: Add an Offline state.
class Offline extends Result and a switch case.
HARDReal project: geometry and graphics toolsExample 10 of 10

Shapes with patterns

Switch with object patterns picks the right area formula by type.
sealed class Shape {}
class Circle extends Shape {
  final double r;
  Circle(this.r);
}
class Rect extends Shape {
  final double w, h;
  Rect(this.w, this.h);
}
class Tri extends Shape {
  final double b, h;
  Tri(this.b, this.h);
}
double area(Shape s) => switch (s) {
  Circle(r: var r) => 3.14159 * r * r,
  Rect(w: var w, h: var h) => w * h,
  Tri(b: var b, h: var h) => 0.5 * b * h,
};
void main() {
  var shapes = <Shape>[Circle(3), Rect(4, 5), Tri(6, 7)];
  for (var s in shapes) {
    print('${s.runtimeType}: ${area(s).toStringAsFixed(2)}');
  }
}
Try it yourself: Add a Square shape.
class Square extends Shape and a case.

Quick quiz

3 questions. Click an answer.
What is Status.shipped.name?
'Status''shipped'2null
What does var (a, b) = (1, 2); do?
Makes a listUnpacks a record into a and bAdds 1 and 2Error
What must a switch over a sealed class do?
Use defaultHandle every child typeReturn voidUse break
Score: 0 / 3

Recap: what you learned in Module 12

enum

Fixed named choices. name, index and values.

Enhanced enum

Values can carry fields and methods.

Records

(a, b) bundles values; $1, $2 or named fields.

Destructuring

Unpack records, lists and maps in one line.

switch expression

Returns a value; patterns, guards and _.

sealed

Closed family; switch must cover every case.

Next: the next part of the course.

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