COMPLETE FLUTTER COURSE · BRAINBIT INFOTECH

Part 1

4 modules · 15 class hours · 40 practical examples

Module 1: Welcome to Flutter

Meet Flutter, Dart and your very first app · 3 h

Module 2: Dart Basics

Variables, numbers, text, decisions and loops · 4 h

Module 3: Functions and Collections

Reuse code with functions, store many values in List, Map and Set · 4 h

Module 4: Object-Oriented Dart and Async

Classes, inheritance, enums, Future, async/await and exceptions · 4 h

MODULE 1 · PART 1

Welcome to Flutter

Meet Flutter, Dart and your very first app
You will learn
  • What Flutter is and why companies use it
  • What a widget is (everything in Flutter is a widget)
  • How a Flutter project is organised
  • Write and change your first app
  • Use Hot Reload to see changes in a second
You will build: a Hello Ranchi welcome screen and a digital visiting card
3 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
💙

Where is this used in real apps?

Flutter is used by Google Pay, BMW, Alibaba and thousands of Indian start-ups. One code makes an Android app, an iPhone app and a website.

Local shop apps

A kirana store in Ranchi can have its own Android app: product list, offers and a call button.

College and coaching apps

Timetable, notice board and fee receipts for students, like the apps coaching institutes use.

Startup MVPs

Build the first version of an idea in weeks, on Android and iPhone together.

Ranchi Kirana
🌾
Atta 5 kg
Main Road, Ranchi
Rs 245
🍲
Toor Dal 1 kg
In stock
Rs 158
🧴
Mustard Oil 1 L
Fast delivery
Rs 172
🥛
Fresh Milk 500 ml
Today
Rs 31
+
🏠
Home
🛒
Cart
👤
Me

What is Flutter?

A toolkit from Google

Flutter is a free toolkit to build apps. You write code once and it runs on Android, iPhone, web and Windows.

One code, many screens

Without Flutter you need one team for Android and another for iPhone. With Flutter, one team is enough.

Fast and smooth

Flutter draws every pixel itself, so apps run at 60 frames per second and look the same on every phone.

Free and open source

Flutter costs nothing. Lakhs of developers use it, so you will always find help and packages.

Think of it like this: Flutter is a box of colourful LEGO bricks. You join small bricks (widgets) to make a big app.

Flutter and Dart

Flutter is the toolkit. Dart is the language you write in. If you learned Java, C or JavaScript, Dart will feel familiar.

Easy to read

Dart reads almost like English: print('Namaste');

Fast

Dart is compiled to real machine code, so the app opens quickly.

Safe

Dart checks types, so many mistakes are caught before the app runs.

Do not worry: Modules 2, 3 and 4 teach Dart from zero. You do not need to know it now.

Everything is a Widget

A widget is a small building block of the screen: a piece of text, a button, a picture, even the empty space between two things. The whole app is widgets inside widgets.

Here Center, Text and Scaffold are all widgets. Each one sits inside another.
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Center(
        child: Text('I am a widget!',
            style: TextStyle(fontSize: 30)),
      ),
    ),
  ));
}

The Widget Tree

Widgets inside widgets make a tree, like a family tree. The top is the parent, the ones inside are children. The animation on the next slide shows how a screen grows from this tree.

Parent

A widget that holds others, such as Column.

Child

A widget placed inside, such as Text.

Tree

All widgets together, from MaterialApp at the top to the smallest Text.

Remember: to change how the screen looks, you only change the tree. Flutter redraws the rest.

Set up your computer (once)

1. Install Flutter SDK

Download from flutter.dev, unzip to C:\src\flutter and add its bin folder to PATH.

2. Install an editor

Android Studio (with the Flutter plugin) or VS Code with the Flutter extension. Both are free.

3. Run flutter doctor

Open a terminal and type flutter doctor. It lists what is missing, with green ticks when ready.

4. Create a phone

In Android Studio open Device Manager and create an emulator, or plug in your own Android phone with USB debugging on.

No installation yet? Do not wait. Use the Code Lab (press L) inside this course to run every example in your browser.

Your first project folder

Create a project with one command in the terminal:

flutter create my_app
cd my_app
flutter run

Almost all the time you work only in lib/main.dart and pubspec.yaml.

pubspec.yaml is the shopping list of your app: its name, version, the packages and the images it needs.
my_app/
  lib/
    main.dart        <- your Dart code lives here
  android/           <- Android settings (rarely touched)
  ios/               <- iPhone settings
  web/               <- website files
  test/              <- automatic tests
  pubspec.yaml       <- app name, packages, images

Anatomy of the first app

Read it like a story: start at main → runApp shows MyApp → MaterialApp → Scaffold (page with top bar and body).
void main() {                 // 1. the app starts here
  runApp(const MyApp());      // 2. put MyApp on screen
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(       // 3. Material design app
      home: Scaffold(         // 4. page skeleton
        appBar: AppBar(title: const Text('Namaste')),
        body: const Center(child: Text('Hello Flutter')),
      ),
    );
  }
}

Hot Reload: your best friend

Hot Reload

Save the file (Ctrl+S) and the screen updates in about one second. Your data stays. Shortcut: r in the terminal.

Hot Restart

Starts the app again from the beginning. Use it after changing main() or app state. Shortcut: R.

Full Run

Stop and run again. Needed after adding a package or an image to pubspec.yaml.

Tip: Change a colour, press Save, and watch the phone change. This quick loop is why Flutter is so loved.

How to use this course

1. Watch the animation

Each hard idea has a step-by-step animation. Press Next or Auto play.

2. Run the example

Every example has a live phone or console. Tap buttons on the phone: it really works.

3. Try it yourself

Each example ends with a small task. Open it in the Lab, change the code, press Run.

4. Keys

Arrow keys move slides, M menu, L Code Lab, F full screen. Buttons are at the bottom right.

Honest note: the phones in these slides are drawn by a small Flutter-like engine inside this page. It follows real Flutter rules, but fonts and a few details can differ on a real device.

Animated explainer: From your code to the phone screen

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

Animated explainer: The widget tree grows

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

Animated explainer: Hot Reload in action

Press Next to walk through it step by step, or Auto play.
EASYReal project: splash / welcome message of any appExample 1 of 10

Hello Ranchi text

The smallest Flutter app: show one line of text in the middle of the screen. Every big app starts like this. Text shows words, Center puts it in the middle.
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Center(
        child: Text(
          'Hello Ranchi!',
          style: TextStyle(fontSize: 34),
        ),
      ),
    ),
  ));
}
Try it yourself: Change the text to your own name and make the font size 48.
Edit the words inside Text('...') and the number after fontSize.
EASYReal project: coloured banner on a home pageExample 2 of 10

Welcome banner with colours

A Container is a box. You can give it a background colour, space inside (padding) and a child. Banners and offer strips in shopping apps are made like this.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
        child: Container(
          color: Colors.deepOrange,
          padding: const EdgeInsets.all(24),
          child: const Text(
            'Welcome to BrainBit Infotech',
            style: TextStyle(
              fontSize: 26,
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    ),
  ));
}
Try it yourself: Change the banner colour to Colors.green and the padding to 40.
Colors.green, Colors.blue, Colors.purple all work. Padding is the number inside EdgeInsets.all().
EASYReal project: top title bar of every screenExample 3 of 10

App with an AppBar

The AppBar is the bar at the top with the screen title, like in WhatsApp or Paytm. A Scaffold gives you the places for it: appBar at the top, body below.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: const Text('Ranchi Bazaar'),
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
      ),
      body: const Center(
        child: Text('Fresh vegetables today'),
      ),
    ),
  ));
}
Try it yourself: Change the title to your shop name and the bar colour to Colors.indigo.
Change title: Text(...) and backgroundColor.
EASYReal project: profile / info card in an appExample 4 of 10

Institute name card

A BoxDecoration makes a Container pretty: rounded corners, a border and a soft shadow. This is how cards in apps get their look.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
        child: Container(
          padding: const EdgeInsets.all(28),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: Colors.blue, width: 2),
            boxShadow: const [
              BoxShadow(color: Colors.black26, blurRadius: 10),
            ],
          ),
          child: const Text('BrainBit Infotech, Ranchi',
              style: TextStyle(fontSize: 22)),
        ),
      ),
    ),
  ));
}
Try it yourself: Make the corners more round (radius 40) and the border red.
BorderRadius.circular(40) and Border.all(color: Colors.red).
EASYReal project: name, course and city on a student cardExample 5 of 10

Three lines with Column

A Column places widgets one below another. A Row places them side by side. These two are the most used widgets in Flutter.
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Asha Kumari', style: TextStyle(fontSize: 28)),
            Text('Flutter Course'),
            Text('Ranchi, Jharkhand'),
          ],
        ),
      ),
    ),
  ));
}
Try it yourself: Add a fourth line with your phone number.
Add one more Text('...'), separated by a comma, inside children: [ ].
MEDIUMReal project: call / mail / location bar on a shop pageExample 6 of 10

Contact bar with Row

Row puts icons and texts side by side. mainAxisAlignment.spaceAround shares the free space equally. Almost every business app has this contact strip.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: const Text('Contact us')),
      body: Container(
        color: Colors.blue.shade50,
        padding: const EdgeInsets.all(16),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Column(children: [Icon(Icons.phone, size: 36), Text('Call')]),
            Column(children: [Icon(Icons.mail, size: 36), Text('Mail')]),
            Column(children: [Icon(Icons.location_on, size: 36), Text('Map')]),
          ],
        ),
      ),
    ),
  ));
}
Try it yourself: Add a fourth item for WhatsApp using Icons.chat.
Copy one Column(...) line, change the icon to Icons.chat and the text to WhatsApp.
MEDIUMReal project: profile screen of a school / coaching appExample 7 of 10

Student profile header

We join Row and Column: an icon on the left, name and class on the right. Putting small widgets inside bigger ones is the heart of Flutter design.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: const Text('My Profile')),
      body: Container(
        padding: const EdgeInsets.all(20),
        color: Colors.indigo.shade50,
        child: const Row(
          children: [
            Icon(Icons.account_circle, size: 80, color: Colors.indigo),
            SizedBox(width: 16),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Rohit Singh', style: TextStyle(fontSize: 24)),
                Text('Class 10 - DAV Public School'),
                Text('Roll No: 27'),
              ],
            ),
          ],
        ),
      ),
    ),
  ));
}
Try it yourself: Show your own name, class and school.
Replace the three Text lines inside the Column.
MEDIUMReal project: "Add to cart" confirmation messageExample 8 of 10

Floating button shows a message

The round FloatingActionButton sits above the screen. When tapped it shows a SnackBar, the small message at the bottom. Shopping apps use this for "Item added".
void main() => runApp(const MaterialApp(home: Home()));

class Home extends StatelessWidget {
  const Home({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Cart demo')),
      body: const Center(child: Text('Tap the + button')),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Item added to cart')),
          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
Try it yourself: Change the message to "Order placed" and the button icon to Icons.shopping_cart.
Edit the SnackBar Text and Icons.shopping_cart.
HARDReal project: business card screen for a freelancer / shop ownerExample 9 of 10

Digital visiting card

A real mini-design: gradient card, big icon, name, role and contact rows. It uses everything from this module: Container, Column, Row, Icon, Text and decoration.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      backgroundColor: Colors.blueGrey.shade900,
      body: Center(
        child: Container(
          width: 300,
          padding: const EdgeInsets.all(22),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(22),
            gradient: const LinearGradient(
              colors: [Color(0xFF0B6BFF), Color(0xFF8E5DE8)],
            ),
          ),
          child: const Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.account_circle, size: 90, color: Colors.white),
              Text('Nandan Kumar', style: TextStyle(fontSize: 26, color: Colors.white)),
              Text('Trainer, BrainBit Infotech', style: TextStyle(color: Colors.white70)),
              SizedBox(height: 14),
              Row(children: [Icon(Icons.phone, color: Colors.white), SizedBox(width: 8), Text('+91 98xxx xxxxx', style: TextStyle(color: Colors.white))]),
              Row(children: [Icon(Icons.location_on, color: Colors.white), SizedBox(width: 8), Text('Ranchi, Jharkhand', style: TextStyle(color: Colors.white))]),
            ],
          ),
        ),
      ),
    ),
  ));
}
Try it yourself: Make it your own card: change the name, role and add an email row with Icons.mail.
Copy a Row(...) line, change the icon and the text.
HARDReal project: first screen shown when an app opensExample 10 of 10

Splash screen layout

A splash screen shows the logo, name and a tagline. We put the logo in the middle and "from BrainBit Infotech" at the bottom. Expanded pushes the last line to the bottom edge.
void main() {
  runApp(MaterialApp(
    home: Scaffold(
      backgroundColor: Colors.teal,
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.shopping_basket, size: 110, color: Colors.white),
                    SizedBox(height: 12),
                    Text('Ranchi Mart', style: TextStyle(fontSize: 36, color: Colors.white, fontWeight: FontWeight.bold)),
                    Text('Fresh at your door', style: TextStyle(color: Colors.white70, fontSize: 18)),
                  ],
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 20),
              child: Text('from BrainBit Infotech', style: TextStyle(color: Colors.white70)),
            ),
          ],
        ),
      ),
    ),
  ));
}
Try it yourself: Change the app name, colour and icon (try Icons.school or Icons.local_hospital).
Change backgroundColor, the Icons.xxx name and the two Text lines.

Quick quiz

3 questions. Click an answer.
Which language do we use to write Flutter apps?
JavaDartPythonC
In Flutter, almost everything on the screen is a...
WidgetImageButton onlyDatabase
Which key press shows the change in the app in about one second?
Hot ReloadFormatDeleteInstall
Score: 0 / 3

Recap: what you learned in Module 1

Flutter

One code for Android, iPhone, web and desktop.

Dart

The language of Flutter, easy to read.

Widgets

Small building blocks; the whole app is a tree of them.

Project

You mostly work in lib/main.dart and pubspec.yaml.

Starting point

main() calls runApp(), which shows MaterialApp and Scaffold.

Hot Reload

Save and see the change in one second.

Next: Dart Basics - Variables, numbers, text, decisions and loops
MODULE 2 · PART 1

Dart Basics

Variables, numbers, text, decisions and loops
You will learn
  • Store data in variables (int, double, String, bool)
  • Do calculations with operators
  • Join text with string interpolation
  • Make decisions with if / else and switch
  • Repeat work with for and while loops
You will build: a GST bill, a grade calculator and an electricity bill program
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎯

Where is this used in real apps?

Before the screen, every app needs logic: totals, discounts, grades, bills. That logic is plain Dart code.

Billing and GST

Every shop app adds price x quantity, then GST, then discount. That is variables and operators.

Result and grade apps

Schools turn marks into grades using if / else. Same code, different data.

Loops everywhere

Showing 100 products, sending 500 reminders, building a table: all done with loops.

Bill Calculator
🧾
Subtotal
3 items
Rs 3600
💰
GST 18%
Tax
Rs 648
🎫
Discount
Festival offer
- Rs 200
✅
Total to pay
UPI / Cash
Rs 4048

Your first Dart program

Every Dart program starts at main(). print() shows a line of text in the output. Each instruction ends with a semicolon ;.

Tip: Output appears in the dark box on the right. Change a number and press Run again.
void main() {
  print('Namaste Ranchi!');
  print(2 + 3);
  print('Total = ${10 * 5}');
}

Variables: labelled boxes

A variable is a box with a label. The label is the name; inside is a value. You choose the type of value the box can hold.

int

Whole numbers: int age = 17;

double

Numbers with a decimal point: double price = 49.5;

String

Text in quotes: String city = 'Ranchi';

bool

Only true or false: bool isPaid = true;

var, final, const: var lets Dart guess the type. final is set once and never changed. const is fixed even before the app runs.

Text with $ interpolation

Put $name inside quotes to insert a variable. Use ${...} for a calculation. This is easier than joining with +.

A string can use single or double quotes. Use \n for a new line.
void main() {
  String name = 'Asha';
  int age = 17;
  double fee = 2499.5;

  print('Name: $name');
  print('Next year $name will be ${age + 1}');
  print('Fee with GST: ${fee * 1.18}');
  print('Name length: ${name.length}');
  print(name.toUpperCase());
}

Operators: do the maths

Arithmetic

+ - * / and % (remainder). 10 / 4 is 2.5, but 10 ~/ 4 is 2 (whole part only).

Comparison

== != > < >= <= give true or false: age >= 18.

Logical

&& (and), || (or), ! (not): age >= 18 && hasId.

Short forms

count++, total += 50, x *= 2 save typing.

Remember: one = stores a value, two == compares two values.

Decisions: if, else and switch

The program checks conditions from top to bottom and runs only the first block that is true. Use switch when one value has many exact choices.

Real use: apps decide: is the user logged in? is the cart empty? is the age above 18?
int marks = 72;

if (marks >= 80) {
  print('Distinction');
} else if (marks >= 40) {
  print('Pass');
} else {
  print('Fail');
}

int day = 7;
switch (day) {
  case 6:
  case 7:
    print('Weekend');
    break;
  default:
    print('Working day');
}

Loops: repeat without typing again

A loop repeats a block of code. break stops the loop early, continue skips to the next round.

Real use: show 50 products from a list, send reminders to every student, print every row of a report.
// for: when you know how many times
for (int i = 1; i <= 3; i++) {
  print('Day $i');
}

// while: repeat while a condition is true
int n = 3;
while (n > 0) {
  print('Countdown $n');
  n--;
}

// for-in: go through a list
for (String c in ['Ranchi', 'Patna', 'Gaya']) {
  print(c);
}

Null safety: a value may be missing

What is null?

null means "no value". A student may not have an email yet.

Question mark type

String? email; means the box may hold text or null.

?? gives a default

email ?? 'not given' uses the default when email is null.

?. is safe access

email?.length returns null instead of crashing.

Why it matters: "null" mistakes crashed many apps. Dart forces you to think about them, so your app stays safe.

Reading errors and writing neat code

Red error text is a friend

It tells the line number and the problem. Read the first line first.

Common mistakes

Missing ;, wrong spelling (Print vs print), unclosed brackets.

Names

Use camelCase for variables: totalMarks. Use clear names, not x1.

Comments

// note explains code to humans. Dart ignores it.

Habit: run your code after every small change. Small steps make errors easy to find.

Animated explainer: A variable is a labelled box

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

Animated explainer: How if / else chooses a path

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

Animated explainer: A for loop, round by round

Press Next to walk through it step by step, or Auto play.
EASYReal project: welcome message / first log line of any programExample 1 of 10

Namaste print

print() shows text in the output. Developers use it every day to see what the program is doing. Each line of code ends with a semicolon.
void main() {
  print('Namaste, Ranchi!');
  print('Welcome to the Flutter course');
  print('BrainBit Infotech');
}
Try it yourself: Print your own name and your school or college on two lines.
Add print('Your text'); lines inside main().
EASYReal project: result card of a school / coaching appExample 2 of 10

Marks with variables

We store marks in int variables, add them, and find the average as a double. toStringAsFixed(1) keeps one digit after the point.
void main() {
  String name = 'Asha';
  int maths = 82;
  int science = 76;
  int english = 90;

  int total = maths + science + english;
  double average = total / 3;

  print('$name scored $total out of 300');
  print('Average: ${average.toStringAsFixed(1)}');
}
Try it yourself: Add a fourth subject, Hindi, and calculate the total and average out of 400.
Add int hindi = 70; then add it to total and divide by 4.
EASYReal project: billing app of a shopExample 3 of 10

GST bill

Price x quantity gives the subtotal. GST is a percentage of the subtotal. Every billing and invoice app does exactly these three lines of maths.
void main() {
  double price = 1200;
  int quantity = 3;

  double subtotal = price * quantity;
  double gst = subtotal * 18 / 100;
  double total = subtotal + gst;

  print('Subtotal : Rs ${subtotal.toStringAsFixed(2)}');
  print('GST 18%  : Rs ${gst.toStringAsFixed(2)}');
  print('Total    : Rs ${total.toStringAsFixed(2)}');
}
Try it yourself: Change the price to 899 and quantity to 5. Then change GST to 12%.
Edit price, quantity and the number 18 in the gst line.
EASYReal project: ID card / certificate generatorExample 4 of 10

Student ID card text

final variables cannot change after they are set, perfect for a roll number. String interpolation joins everything into neat lines.
void main() {
  final String name = 'Pooja Sahu';
  final int roll = 27;
  const String course = 'Flutter App Development';
  String city = 'Ranchi';

  print('--------------------');
  print('Name   : $name');
  print('Roll   : $roll');
  print('Course : $course');
  print('City   : ${city.toUpperCase()}');
  print('--------------------');
}
Try it yourself: Try changing roll inside main with roll = 30; and read the error. Then fix it.
final cannot be changed. The error is useful: it protects your data.
EASYReal project: age check in a sign-up formExample 5 of 10

Voting eligibility

if / else lets the program decide. The condition age >= 18 is true or false. Apps use this for age checks, login checks and offers.
void main() {
  int age = 17;

  if (age >= 18) {
    print('You can vote. Please carry your Voter ID.');
  } else {
    int wait = 18 - age;
    print('Not yet. Wait $wait more year(s).');
  }
}
Try it yourself: Change age to 25, then add a message for age 60 and above.
Add else if (age >= 60) { ... } before else.
MEDIUMReal project: report card of a school appExample 6 of 10

Grade calculator

A chain of else if checks goes from the highest limit to the lowest. The first true condition wins. && (and) joins two checks.
void main() {
  int marks = 76;
  String grade;

  if (marks >= 90) {
    grade = 'A+';
  } else if (marks >= 75) {
    grade = 'A';
  } else if (marks >= 60) {
    grade = 'B';
  } else if (marks >= 40) {
    grade = 'C';
  } else {
    grade = 'Fail';
  }

  bool passed = marks >= 40;
  print('Marks: $marks  Grade: $grade');
  print(passed ? 'Result: PASS' : 'Result: FAIL');
}
Try it yourself: Test marks 95, 39 and 60. Is the grade right every time?
Change the number in marks and press Run again each time.
MEDIUMReal project: practice-sheet generator in a school appExample 7 of 10

Multiplication table

A for loop repeats a line. Here i goes from 1 to 10 and each round prints one row of the table.
void main() {
  int n = 7;
  print('Table of $n');
  for (int i = 1; i <= 10; i++) {
    print('$n x $i = ${n * i}');
  }
}
Try it yourself: Print the table of 12. Then make it count up to 20 rows.
Change n to 12 and the number in i <= 10.
MEDIUMReal project: shop-timing / holiday notice in an appExample 8 of 10

Day of the week with switch

switch is best when one value has many exact choices. Cases 6 and 7 share the same block, so Saturday and Sunday both print "Weekend".
void main() {
  int day = 3;
  String name;

  switch (day) {
    case 1: name = 'Monday'; break;
    case 2: name = 'Tuesday'; break;
    case 3: name = 'Wednesday'; break;
    case 4: name = 'Thursday'; break;
    case 5: name = 'Friday'; break;
    case 6:
    case 7: name = 'Weekend'; break;
    default: name = 'Invalid day';
  }

  print('Day $day is $name');
  print(day <= 5 ? 'Office open 10 AM - 6 PM' : 'Closed');
}
Try it yourself: Test days 6 and 9. What do you see?
Change int day = 3; to 6, then to 9.
HARDReal project: utility / bill-payment appExample 9 of 10

Electricity bill with slabs

Real bills use slabs: the first units cost less and later units cost more. We use if / else if and careful arithmetic. (Rates here are sample numbers, not the real tariff.)
void main() {
  int units = 260;
  double bill = 0;

  if (units <= 100) {
    bill = units * 3.5;
  } else if (units <= 200) {
    bill = 100 * 3.5 + (units - 100) * 5.0;
  } else {
    bill = 100 * 3.5 + 100 * 5.0 + (units - 200) * 6.5;
  }

  double fixedCharge = 100;
  double duty = bill * 5 / 100;
  double total = bill + fixedCharge + duty;

  print('Units used : $units');
  print('Energy     : Rs ${bill.toStringAsFixed(2)}');
  print('Fixed      : Rs ${fixedCharge.toStringAsFixed(2)}');
  print('Duty 5%    : Rs ${duty.toStringAsFixed(2)}');
  print('Total bill : Rs ${total.toStringAsFixed(2)}');
}
Try it yourself: Test with 80, 150 and 420 units. Check the bill by hand for 150 units.
150 units = 100 x 3.5 + 50 x 5.0 = 600 energy charge.
HARDReal project: logic round of job interviewsExample 10 of 10

FizzBuzz and prime numbers

A famous interview exercise: loops, remainder % and nested loops together. The second part uses a loop inside a loop and break to stop early.
void main() {
  for (int i = 1; i <= 15; i++) {
    if (i % 15 == 0) {
      print('FizzBuzz');
    } else if (i % 3 == 0) {
      print('Fizz');
    } else if (i % 5 == 0) {
      print('Buzz');
    } else {
      print(i);
    }
  }

  String primes = '';
  for (int n = 2; n <= 30; n++) {
    bool isPrime = true;
    for (int d = 2; d * d <= n; d++) {
      if (n % d == 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) primes += '$n ';
  }
  print('Primes up to 30: $primes');
}
Try it yourself: Find all prime numbers up to 100.
Change n <= 30 to n <= 100.

Quick quiz

3 questions. Click an answer.
Which variable type holds the value 49.5?
intdoubleboolString
What does 10 ~/ 4 give in Dart?
2.5236
Which code prints "Hello Asha" for String name = 'Asha';?
print('Hello name');print('Hello $name');print('Hello' name);print(Hello $name);
Score: 0 / 3

Recap: what you learned in Module 2

Variables

int, double, String, bool store data. final and const never change.

Interpolation

$name and ${a + b} put values inside text.

Operators

+ - * / % ~/ and comparison, logical operators.

Decisions

if / else if / else, switch for many exact choices.

Loops

for, while and for-in repeat work; break and continue control them.

Null safety

String? may be null; ?? gives a default value.

Next: Functions and Collections - Reuse code with functions, store many values in List, Map and Set
MODULE 3 · PART 1

Functions and Collections

Reuse code with functions, store many values in List, Map and Set
You will learn
  • Write functions with parameters and return values
  • Use named, optional and default parameters
  • Store many values in List, Map and Set
  • Transform data with map, where, fold and sort
  • Handle missing values safely
You will build: a shopping-cart total and an attendance report
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🧰

Where is this used in real apps?

Apps show lists of things: products, students, messages. Functions and collections are how Dart stores and handles them.

List = a row of items

Cart items, chat messages, news headlines: all are lists.

Map = labelled data

A student is a map: name, roll, city. A JSON reply from the internet is also a map.

Functions = tools

Write the GST rule once as a function and use it on every screen.

My Cart (3)
📓
Notebook x4
Rs 45 each
Rs 180
🖊
Pen box
Rs 120
Rs 120
🎒
School bag
Rs 650
Rs 650
✅
Total
Free delivery
Rs 855

Functions: write once, use many times

A function is a named block of code. You give it input (parameters), it does work and can give back a result (return value).

Real use: one addGst() used on the cart, the bill and the invoice. Change the rule once, every screen is correct.
// returns nothing (void)
void greet(String name) {
  print('Namaste $name!');
}

// returns a number
double addGst(double price) {
  return price * 1.18;
}

// short form with =>
double square(double x) => x * x;

void main() {
  greet('Asha');
  print(addGst(100).toStringAsFixed(2));
  print(square(7).toStringAsFixed(0));
}

Parameters: positional, named, default

Named parameters in { } make calls easy to read. required means you must give it. A default value (= 18) is used when you skip it.

This is everywhere in Flutter: Text('Hi', style: ...) uses named parameters. You will see them on every widget.
// positional: order matters
int add(int a, int b) => a + b;

// named: use the names when calling
String card({required String name, int age = 18}) {
  return '$name ($age)';
}

// optional positional in [ ]
String hello(String name, [String city = 'Ranchi']) {
  return '$name from $city';
}

void main() {
  print(add(2, 3));
  print(card(name: 'Asha'));
  print(card(age: 21, name: 'Rohit'));
  print(hello('Pooja'));
  print(hello('Vikash', 'Gaya'));
}

List: an ordered row of items

A List holds many values in order. Counting starts from 0.

A RangeError means you asked for an index that does not exist, like fruits[10] in a list of 4.
void main() {
  List<String> fruits = ['Apple', 'Banana', 'Mango'];
  fruits.add('Guava');          // add at end
  fruits.insert(1, 'Litchi');   // add at position 1
  fruits.remove('Banana');      // remove a value

  print(fruits);
  print(fruits[0]);             // first item
  print(fruits.length);
  print(fruits.contains('Mango'));
}

Map: labelled data (key and value)

A Map stores pairs: a key (label) and its value. You find a value by its key, not by position.

Big idea: data from the internet (JSON) arrives as Maps and Lists. You will use this in Module 14.
void main() {
  Map<String, String> student = {
    'name': 'Asha',
    'city': 'Ranchi',
    'course': 'Flutter',
  };
  student['age'] = '17';          // add
  student['city'] = 'Dhanbad';    // change

  print(student['name']);
  print(student.containsKey('age'));
  student.forEach((k, v) => print('$k -> $v'));
}

Set: no duplicates allowed

What it does

A Set keeps each value only once: {1, 2, 2, 3} becomes {1, 2, 3}.

Create it

Set<String> tags = {'a', 'b'}; or list.toSet().

Useful methods

add, contains, union, intersection, difference.

Real use

Unique tags, selected checkboxes, distinct cities of all orders.

Rule of thumb: need order and duplicates? List. Need labels? Map. Need uniqueness? Set.

Power tools: map, where, fold, sort

These methods take a small function (lambda) and apply it to every item. They replace long loops with one line.

Flutter link: list.map((item) => Text(item)).toList() turns data into widgets. You will use it in Module 8.
void main() {
  List<int> prices = [45, 120, 80, 250];

  var cheap = prices.where((p) => p < 100).toList();
  var gst = prices.map((p) => p * 1.18).toList();
  int total = prices.fold(0, (sum, p) => sum + p);
  prices.sort((a, b) => b.compareTo(a));  // high to low

  print(cheap);
  print(total);
  print(prices);
  prices.forEach((p) => print('Rs $p'));
}

Collection if, for and spread

Dart lets you put if, for and ... (spread) right inside a list. Flutter uses this a lot to show a widget only when needed.

Real use: show a "Logout" button only if the user is logged in.
void main() {
  bool isMember = true;
  List<String> menu = [
    'Home',
    'Courses',
    if (isMember) 'My Certificates',   // collection if
    for (int i = 1; i <= 2; i++) 'Batch $i',
    ...['Contact', 'About'],          // spread
  ];
  print(menu);
}

Missing values with null safety

Nullable

String? email; may be null.

Default value

email ?? 'not given'

Safe call

email?.length gives null, not a crash.

Assign if null

email ??= 'guest@x.in';

Why: forms, API replies and databases often have missing fields. Safe code never crashes on them.

Animated explainer: What happens when you call a function

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

Animated explainer: A List is a row of numbered boxes

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

Animated explainer: where, map and fold on a list

Press Next to walk through it step by step, or Auto play.
EASYReal project: welcome message in every app screenExample 1 of 10

A function that greets

A function is written once and called many times. void means it returns nothing; it only does something (prints). Parameters bring in the data.
void greet(String name) {
  print('Namaste $name, welcome to BrainBit Infotech!');
}

void main() {
  greet('Asha');
  greet('Rohit');
  greet('Pooja');
}
Try it yourself: Add a second parameter city and print "Namaste Asha from Ranchi".
void greet(String name, String city) and call greet('Asha', 'Ranchi').
EASYReal project: real-estate / property appExample 2 of 10

Plot area and cost

These functions return a value, so the result can be used later. => is a short way to write a function with one line.
double area(double length, double width) => length * width;

double cost(double sqFt, double rate) => sqFt * rate;

void main() {
  double a = area(30, 40);
  double c = cost(a, 1800);

  print('Plot area: ${a.toStringAsFixed(0)} sq ft');
  print('Cost: Rs ${c.toStringAsFixed(0)}');
  print('That is ${(c / 100000).toStringAsFixed(1)} lakh');
}
Try it yourself: Find the cost of a 25 x 50 plot at Rs 2200 per sq ft.
Call area(25, 50) and cost(a, 2200).
EASYReal project: checkout screen with discountExample 3 of 10

Named parameters bill

required named parameters must be given. Parameters with a default value (qty = 1) are optional. Calls are easy to read because each value has its name.
double finalBill({
  required double price,
  int qty = 1,
  double discount = 0,
}) {
  double total = price * qty;
  return total - total * discount / 100;
}

void main() {
  print(finalBill(price: 500).toStringAsFixed(2));
  print(finalBill(price: 500, qty: 3).toStringAsFixed(2));
  print(finalBill(price: 500, qty: 3, discount: 10).toStringAsFixed(2));
}
Try it yourself: Call finalBill with qty: 2 and discount: 25. What do you get?
finalBill(price: 500, qty: 2, discount: 25) gives 750.00.
EASYReal project: cart / to-do / wish listExample 4 of 10

Shopping list with List

A List keeps items in order. add, insert and remove change it. We loop with an index to print numbered lines.
void main() {
  List<String> items = ['Atta', 'Dal', 'Rice'];
  items.add('Salt');
  items.insert(0, 'Milk');
  items.remove('Dal');

  print(items);
  print('Total items: ${items.length}');
  print('First: ${items.first}, Last: ${items.last}');

  for (int i = 0; i < items.length; i++) {
    print('${i + 1}. ${items[i]}');
  }
}
Try it yourself: Add Sugar at the end and remove Rice. Print the list again.
items.add('Sugar'); items.remove('Rice');
EASYReal project: student record / JSON dataExample 5 of 10

Marks in a Map

A Map finds a value by its key. forEach visits every pair. This is exactly the shape of JSON data that apps receive from servers.
void main() {
  Map<String, int> marks = {
    'Maths': 82,
    'Science': 76,
    'English': 90,
  };
  marks['Hindi'] = 68;
  marks['Maths'] = 85;

  marks.forEach((subject, m) => print('$subject: $m'));
  print('Subjects: ${marks.keys.toList()}');
  print('Has Hindi? ${marks.containsKey('Hindi')}');
}
Try it yourself: Add Computer: 95 and print the highest mark using marks.values.reduce.
marks['Computer'] = 95; then print(marks.values.reduce((a, b) => a > b ? a : b));
MEDIUMReal project: price-filter on a shopping pageExample 6 of 10

Filter cheap items

where keeps items that pass a test, map changes each item, sort orders them. Shopping apps use these for filters, GST price and "sort by price".
void main() {
  List<int> prices = [45, 120, 80, 250, 30, 199];

  var cheap = prices.where((p) => p < 100).toList();
  var withGst = prices.map((p) => (p * 1.18).round()).toList();
  prices.sort();

  print('Cheap: $cheap');
  print('With GST: $withGst');
  print('Sorted: $prices');
  print('Any above 200? ${prices.any((p) => p > 200)}');
}
Try it yourself: Show only prices between 50 and 200.
prices.where((p) => p >= 50 && p <= 200).toList()
MEDIUMReal project: "delivery cities" in an order dashboardExample 7 of 10

Unique cities with Set

A Set removes duplicates. intersection and difference compare two groups, for example the cities where we have orders and the cities where we deliver.
void main() {
  List<String> orders = [
    'Ranchi', 'Patna', 'Ranchi', 'Gaya', 'Patna', 'Ranchi'
  ];
  Set<String> cities = orders.toSet();
  Set<String> delivery = {'Ranchi', 'Patna', 'Dhanbad'};

  print('Orders: ${orders.length}');
  print('Unique cities: $cities');
  print('We can deliver: ${cities.intersection(delivery)}');
  print('Cannot deliver: ${cities.difference(delivery)}');
}
Try it yourself: Add Dhanbad to the orders and see how the Sets change.
Add 'Dhanbad' inside the orders list.
MEDIUMReal project: optional fields in a registration formExample 8 of 10

Null safety in a sign-up form

Not every user fills every field. ? marks a value that may be null; ?? gives a default; ?. is a safe call; ??= fills it only if empty.
void main() {
  String? email;
  String? phone = '9876543210';

  print(email ?? 'Email not given');
  print(email?.length);
  print(phone?.length);

  email ??= 'guest@brainbit-teaching.com';
  print(email);

  Map<String, String?> student = {'name': 'Asha', 'mother': null};
  print(student['mother'] ?? 'Not filled');

  if (phone != null) {
    print('Phone ends with ${phone.substring(6)}');
  }
}
Try it yourself: Make phone null and run again. Does the last if still crash?
Change phone to null: String? phone = null; the if-check protects you.
HARDReal project: attendance tracker for a school / coaching instituteExample 9 of 10

Attendance report

A list of Maps (one per student), a loop, percentage maths and a rule: below 75% is a shortage. This is the heart of a real attendance report.
void main() {
  List<Map<String, dynamic>> students = [
    {'name': 'Asha', 'present': 22, 'total': 26},
    {'name': 'Rohit', 'present': 17, 'total': 26},
    {'name': 'Pooja', 'present': 25, 'total': 26},
    {'name': 'Vikash', 'present': 19, 'total': 26},
  ];

  int shortage = 0;
  for (var s in students) {
    double pct = s['present'] / s['total'] * 100;
    String status = pct >= 75 ? 'OK' : 'SHORTAGE';
    if (pct < 75) shortage++;
    print('${s['name'].padRight(8)} ${pct.toStringAsFixed(1)}%  $status');
  }
  print('Students with shortage: $shortage');
}
Try it yourself: Change the limit to 80% and add a fifth student.
Change 75 in both places and add another {...} map to the list.
HARDReal project: cart and checkout of a shopping appExample 10 of 10

Cart total with fold

fold adds up the whole cart. Then we apply two real rules: 10% discount above Rs 500 and free delivery above Rs 499. This is the checkout logic of e-commerce apps.
void main() {
  List<Map<String, dynamic>> cart = [
    {'item': 'Notebook', 'price': 45, 'qty': 4},
    {'item': 'Pen Box', 'price': 120, 'qty': 1},
    {'item': 'School Bag', 'price': 650, 'qty': 1},
  ];

  int subtotal = cart.fold(0, (sum, i) => sum + i['price'] * i['qty']);
  double discount = subtotal > 500 ? subtotal * 0.10 : 0;
  int delivery = subtotal > 499 ? 0 : 40;
  double total = subtotal - discount + delivery;

  print(cart.map((i) => i['item']).join(', '));
  print('Subtotal : Rs $subtotal');
  print('Discount : Rs ${discount.toStringAsFixed(0)}');
  print('Delivery : Rs $delivery');
  print('Total    : Rs ${total.toStringAsFixed(0)}');
}
Try it yourself: Remove the School Bag and check that discount becomes 0 and delivery Rs 40.
Delete the third map from the cart list.

Quick quiz

3 questions. Click an answer.
In a List with 4 items, what is the index of the last item?
4350
Which collection keeps each value only once?
ListMapSetFunction
What does email ?? 'not given' do when email is null?
crashesreturns not givenreturns nullreturns 0
Score: 0 / 3

Recap: what you learned in Module 3

Functions

Name a block of code, give it parameters, return a result.

Parameters

Positional, [optional], {named} and required, with defaults.

List

Ordered items, index from 0: add, insert, remove, length.

Map and Set

Map = key and value (like JSON). Set = unique values.

map / where / fold

Transform, filter and combine items without long loops.

Null safety

? ?? ?. ??= handle missing values safely.

Next: Object-Oriented Dart and Async - Classes, inheritance, enums, Future, async/await and exceptions
MODULE 4 · PART 1

Object-Oriented Dart and Async

Classes, inheritance, enums, Future, async/await and exceptions
You will learn
  • Model real things with classes and objects
  • Write constructors, methods and getters
  • Reuse code with inheritance and abstract classes
  • Wait for slow work with Future, async and await
  • Handle errors with try / catch / finally
You will build: a bank account and a library system in pure Dart
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🧱

Where is this used in real apps?

Flutter itself is built from classes: every widget is a class. And every app waits for something: the internet, a database, a timer.

Classes = blueprints

A Student, a Product, an Order: each is a class. Each real student becomes an object made from it.

Async = no freezing

While the app waits for a server reply, the screen keeps working. That is async / await.

try / catch = no crashes

If the internet fails, show a friendly message instead of closing the app.

Order #1042
✅
Order placed
10:02 AM
Done
📦
Packed
10:40 AM
Done
🚚
Shipped
Ranchi hub
Now
🏠
Delivered
Expected tomorrow
...

Class and object

A class is a blueprint (like the plan of a house). An object is a real thing built from it (the actual house). One class can make many objects.

Flutter link: Text, Container, Scaffold are all classes. Text('Hi') makes a Text object.
class Student {
  String name = '';
  int roll = 0;

  void introduce() {
    print('I am $name, roll $roll');
  }
}

void main() {
  Student a = Student();
  a.name = 'Asha';
  a.roll = 12;

  Student b = Student();
  b.name = 'Rohit';
  b.roll = 27;

  a.introduce();
  b.introduce();
}

Constructors: build the object with data

A constructor sets up a new object. this.title in the brackets copies the given value into the field. Named constructors give another way to build the object.

You already used this: Text('Hi', style: ...) calls the constructor of Text with a positional and a named argument.
class Course {
  final String title;
  final int hours;
  final double fee;

  // shorthand: this.x sets the field directly
  Course(this.title, this.hours, {this.fee = 4999});

  // named constructor
  Course.free(this.title, this.hours) : fee = 0;

  void show() =>
      print('$title | $hours hrs | Rs ${fee.toStringAsFixed(0)}');
}

void main() {
  Course('Flutter', 80).show();
  Course('Dart', 20, fee: 1999).show();
  Course.free('Demo class', 1).show();
}

Methods, getters and private names

Method

A function inside a class: void deposit(int x).

Getter

Looks like a field, works like a function: double get area => w * h;

Private _name

A name starting with _ is private to its file. Others cannot change it by mistake.

toString()

Decides how print(object) looks. Override it to print nicely.

Why private? A bank balance should change only through deposit() and withdraw() where rules are checked.

enum: a fixed list of choices

An enum lists every allowed choice. Using it prevents spelling mistakes like 'shiped'.

Real use: order status, user role (admin, teacher, student), theme mode (light, dark).
enum OrderStatus { placed, packed, shipped, delivered }

void main() {
  OrderStatus s = OrderStatus.shipped;

  print(s);              // OrderStatus.shipped
  print(s.name);         // shipped
  print(s.index);        // 2

  for (var x in OrderStatus.values) {
    print('${x.index}: ${x.name}');
  }

  if (s == OrderStatus.delivered) {
    print('Enjoy!');
  } else {
    print('On the way');
  }
}

Inheritance: reuse and extend

extends makes a child class that gets everything from the parent and can add or change things. @override replaces a parent method. super calls the parent.

Flutter link: class MyApp extends StatelessWidget means MyApp is a StatelessWidget plus your own build().
class Vehicle {
  String name;
  Vehicle(this.name);
  void start() => print('$name starts');
}

class Car extends Vehicle {
  int seats;
  Car(String name, this.seats) : super(name);

  @override
  void start() {
    super.start();                 // run the parent version
    print('Car with $seats seats ready');
  }
}

void main() {
  Car c = Car('Swift', 5);
  c.start();
}

Abstract classes and polymorphism

An abstract class is a rule: "every Shape must have area()". Polymorphism means we call area() on any shape and each one does it in its own way.

Real use: Payment (UPI, card, cash) all have pay(), but each pays differently.
abstract class Shape {
  double area();                 // no body: children must write it
}

class Circle extends Shape {
  double r;
  Circle(this.r);
  @override
  double area() => 3.14159 * r * r;
}

class Rect extends Shape {
  double w, h;
  Rect(this.w, this.h);
  @override
  double area() => w * h;
}

void main() {
  List<Shape> shapes = [Circle(2), Rect(3, 4)];
  for (Shape s in shapes) {
    print(s.area().toStringAsFixed(2));
  }
}

Future, async and await

Slow work (internet, database, file) returns a Future: a promise of a value later. await waits for it without freezing the app. A function using await must be marked async.

Flutter link: every API call and database read in Modules 14 to 16 returns a Future.
Future<String> fetchName() async {
  await Future.delayed(Duration(seconds: 1));
  return 'Asha';
}

Future<void> main() async {
  print('1. asking server...');
  String name = await fetchName();   // waits here
  print('2. got $name');
  print('3. done');
}

Errors: try, catch, finally

Code inside try may fail. If it does, Dart jumps to catch instead of crashing. finally runs in both cases. throw raises your own error.

Real use: if the server is down, show "No internet" instead of a red error screen.
void main() {
  try {
    int age = int.parse('abc');    // not a number!
    print(age);
  } on FormatException {
    print('Please type digits only');
  } catch (e) {
    print('Something else: $e');
  } finally {
    print('Always runs (clean up here)');
  }

  // your own error
  try {
    throw Exception('Fee not paid');
  } catch (e) {
    print('Caught: $e');
  }
}

Animated explainer: Class = blueprint, objects = real things

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

Animated explainer: Inheritance tree

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

Animated explainer: await: waiting without freezing

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

Class Student

A class bundles data (name, roll) and actions (introduce). We make two objects from one class. Each object keeps its own data.
class Student {
  String name = '';
  int roll = 0;

  void introduce() {
    print('I am $name, roll number $roll');
  }
}

void main() {
  Student s1 = Student();
  s1.name = 'Asha';
  s1.roll = 12;

  Student s2 = Student();
  s2.name = 'Rohit';
  s2.roll = 27;

  s1.introduce();
  s2.introduce();
}
Try it yourself: Add a field city and print it in introduce().
String city = ''; and use $city inside the print text.
EASYReal project: Product / Course model in any appExample 2 of 10

Constructor shorthand

Course(this.title, ...) sets the fields directly, so objects are created in one line. Named parameters and a named constructor give flexible creation.
class Course {
  final String title;
  final int hours;
  final double fee;

  Course(this.title, this.hours, {this.fee = 4999});
  Course.free(this.title, this.hours) : fee = 0;

  void show() {
    print('$title | $hours hrs | Rs ${fee.toStringAsFixed(0)}');
  }
}

void main() {
  Course('Flutter', 80).show();
  Course('Dart', 20, fee: 1999).show();
  Course.free('Demo class', 1).show();
}
Try it yourself: Add a course "Python" with 60 hours and fee 3499.
Course('Python', 60, fee: 3499).show();
EASYReal project: property / land calculatorExample 3 of 10

Rectangle with getters

A getter looks like a field but calculates when you ask. Change width and the area is automatically right. No need to store it.
class Rectangle {
  double width;
  double height;

  Rectangle(this.width, this.height);

  double get area => width * height;
  double get perimeter => 2 * (width + height);
  bool get isSquare => width == height;
}

void main() {
  Rectangle r = Rectangle(30, 40);
  print('Area: ${r.area.toStringAsFixed(0)}');
  print('Perimeter: ${r.perimeter.toStringAsFixed(0)}');
  print('Square? ${r.isSquare}');

  r.width = 40;
  print('New area: ${r.area.toStringAsFixed(0)}');
  print('Square? ${r.isSquare}');
}
Try it yourself: Add a getter diagonal using sqrt (add import 'dart:math';).
double get diagonal => sqrt(width * width + height * height);
EASYReal project: order tracking screenExample 4 of 10

enum OrderStatus

An enum lists every allowed status, so a typo like "shiped" is impossible. switch works with enums and Dart warns if you forget a case.
enum OrderStatus { placed, packed, shipped, delivered }

String message(OrderStatus s) {
  switch (s) {
    case OrderStatus.placed:
      return 'We have received your order';
    case OrderStatus.packed:
      return 'Your items are packed';
    case OrderStatus.shipped:
      return 'Out for delivery in Ranchi';
    case OrderStatus.delivered:
      return 'Delivered. Thank you!';
  }
}

void main() {
  for (var s in OrderStatus.values) {
    print('${s.index + 1}. ${s.name}: ${message(s)}');
  }
}
Try it yourself: Add a new status cancelled and give it a message.
Add cancelled to the enum list and a new case in switch.
EASYReal project: shared base class in a booking appExample 5 of 10

Vehicle and Car

Car extends Vehicle gets name and start() for free. @override changes start() and super.start() still runs the parent code first.
class Vehicle {
  String name;
  int wheels;
  Vehicle(this.name, this.wheels);

  void start() => print('$name is starting...');
}

class Car extends Vehicle {
  int seats;
  Car(String name, this.seats) : super(name, 4);

  @override
  void start() {
    super.start();
    print('Car with $seats seats is ready');
  }
}

void main() {
  Vehicle bike = Vehicle('Splendor', 2);
  Car car = Car('Swift', 5);
  bike.start();
  car.start();
  print('${car.name} has ${car.wheels} wheels');
}
Try it yourself: Create a class Bike extends Vehicle with a field hasCarrier.
class Bike extends Vehicle { bool hasCarrier; Bike(String n, this.hasCarrier) : super(n, 2); }
MEDIUMReal project: payment methods / UI componentsExample 6 of 10

Shapes with polymorphism

Every Shape must have area(). The list holds different shapes, and the loop calls the same method; each class answers in its own way. That is polymorphism.
abstract class Shape {
  String get label;
  double area();
}

class Circle extends Shape {
  double r;
  Circle(this.r);
  @override
  String get label => 'Circle r=${r.toStringAsFixed(0)}';
  @override
  double area() => 3.14159 * r * r;
}

class Rect extends Shape {
  double w, h;
  Rect(this.w, this.h);
  @override
  String get label => 'Rect ${w.toStringAsFixed(0)}x${h.toStringAsFixed(0)}';
  @override
  double area() => w * h;
}

void main() {
  List<Shape> shapes = [Circle(2), Rect(3, 4), Circle(1)];
  for (Shape s in shapes) {
    print('${s.label}: ${s.area().toStringAsFixed(2)}');
  }
}
Try it yourself: Add a Triangle class (half of base x height).
area() => 0.5 * b * h; add Triangle(3, 5) to the list.
MEDIUMReal project: API call: place an order and wait for replyExample 7 of 10

Fake order with async / await

A real server takes time. Future.delayed pretends to be slow. await waits, and the lines after it run only when the answer comes. Watch the output appear step by step.
Future<String> placeOrder(String item) async {
  print('Placing order for $item...');
  await Future.delayed(Duration(seconds: 1));
  return 'Order #1042 placed for $item';
}

Future<void> main() async {
  print('Start');
  String r1 = await placeOrder('Notebook');
  print(r1);
  var results = await Future.wait([
    placeOrder('Pen'),
    placeOrder('Bag'),
  ]);
  print(results);
  print('All done');
}
Try it yourself: Change the delay to 3 seconds and watch the output slow down.
Duration(seconds: 3)
MEDIUMReal project: payment / form validation error handlingExample 8 of 10

try / catch for fee payment

We turn a typing mistake or a business rule into a clear message. on FormatException catches bad numbers, and our own throw handles the rule "fee cannot be negative or zero".
double parseFee(String text) {
  double fee = double.parse(text);
  if (fee <= 0) {
    throw Exception('Fee must be more than zero');
  }
  return fee;
}

void main() {
  List<String> inputs = ['4999', 'abc', '-50', '2500.5'];
  for (String t in inputs) {
    try {
      double fee = parseFee(t);
      print('OK  : Rs ${fee.toStringAsFixed(2)}');
    } on FormatException {
      print('BAD : "$t" is not a number');
    } catch (e) {
      print('RULE: $e');
    } finally {
      print('---');
    }
  }
}
Try it yourself: Add the input "0" and read the message. Then add an upper limit of 100000.
if (fee > 100000) throw Exception('Fee too high');
HARDReal project: wallet / UPI / banking appExample 9 of 10

Bank account class

A real mini-model: a private balance (_balance), methods with rules, a custom exception and a transaction history. Outside code cannot break the rules.
class InsufficientFunds implements Exception {
  final double needed;
  InsufficientFunds(this.needed);
  @override
  String toString() => 'Need Rs ${needed.toStringAsFixed(0)} more';
}

class Account {
  final String holder;
  double _balance = 0;
  final List<String> history = [];

  Account(this.holder);
  double get balance => _balance;

  void deposit(double amt) {
    if (amt <= 0) throw Exception('Invalid amount');
    _balance += amt;
    history.add('+ ${amt.toStringAsFixed(0)}');
  }

  void withdraw(double amt) {
    if (amt > _balance) throw InsufficientFunds(amt - _balance);
    _balance -= amt;
    history.add('- ${amt.toStringAsFixed(0)}');
  }
}

void main() {
  var acc = Account('Asha');
  acc.deposit(5000);
  acc.withdraw(1200);
  try {
    acc.withdraw(9000);
  } catch (e) {
    print('Failed: $e');
  }
  print('${acc.holder} balance: ${acc.balance.toStringAsFixed(2)}');
  print(acc.history);
}
Try it yourself: Add a method transfer(Account to, double amt) that moves money.
withdraw(amt); to.deposit(amt);
HARDReal project: library / inventory management appExample 10 of 10

Library system

Two classes work together: Book and Library. The library keeps a list, searches it, issues and returns books, and reports what is available. This is typical app logic.
class Book {
  final String title;
  final String author;
  bool issued = false;
  Book(this.title, this.author);
}

class Library {
  final List<Book> books = [];

  void add(Book b) => books.add(b);

  bool issue(String title) {
    for (Book b in books) {
      if (b.title == title && !b.issued) {
        b.issued = true;
        return true;
      }
    }
    return false;
  }

  void giveBack(String title) {
    for (Book b in books) {
      if (b.title == title) b.issued = false;
    }
  }

  List<String> get available =>
      books.where((b) => !b.issued).map((b) => b.title).toList();
}

void main() {
  var lib = Library();
  lib.add(Book('Wings of Fire', 'APJ Abdul Kalam'));
  lib.add(Book('Godan', 'Premchand'));
  lib.add(Book('Malgudi Days', 'R K Narayan'));

  print(lib.issue('Godan') ? 'Issued Godan' : 'Not available');
  print(lib.issue('Godan') ? 'Issued Godan' : 'Not available');
  print('Available: ${lib.available}');
  lib.giveBack('Godan');
  print('Available: ${lib.available}');
}
Try it yourself: Add a method countIssued that returns how many books are issued.
int get countIssued => books.where((b) => b.issued).length;

Quick quiz

3 questions. Click an answer.
What is an object?
A blueprintA real thing made from a classA loopA package
Which keyword lets a child class reuse a parent class?
implementsextendsimportstatic
What does await do?
Freezes the whole appWaits for a Future without freezing the screenDeletes the FutureMakes code faster
Score: 0 / 3

Recap: what you learned in Module 4

Class / object

A blueprint and the real things built from it.

Constructors

this.x shorthand, named parameters, named constructors.

Getters and private

get area => ...; and _name for hidden fields.

enum

A fixed list of choices, safe from typing mistakes.

Inheritance

extends, super, @override, abstract and polymorphism.

Async and errors

Future, async / await, and try / catch / finally.

Next: the next part of the course.

Code Lab - write any Dart / Flutter code (Ctrl+Enter to run)