1 / 24
⭐ 0 pts
Start
Vars
Types
Ops
Flow
Fn
Classes
Q1
Q2
Q3
Cart
Project
Guesser
Week 1 · Day 2

Dart
Fundamentals

From reading about Dart to writing it. Every concept gets practiced immediately.

📦 Variables 🏷️ Types & Methods 💬 Strings 🔒 Null Safety ⚙️ Operators 🔀 Control Flow 🔧 Functions 🏗️ Classes & Modifiers 🎮 3 Quizzes + 2 Projects

Press J anytime to jump to any section. Arrow keys to navigate.

Quick warm-up

What did you find in the Dart docs?

Click what you read. If you didn't read — that's ok, we cover everything from scratch today.

📦

Variables

var, final, const — how to store values

⚙️

Operators

+, -, *, /, ==, &&, || — the math of Dart

💬

Comments

// How you leave notes in your code

💡 Even if you didn't read — that's totally fine. Everything is taught from scratch today.

Topic 1 · Variables

Variables — Named Boxes

📦
A variable = a labeled box in memory

You put a value inside. Give it a name. Use that name to get the value later anywhere in your code.

📦
name = "Aayush"
📦
age = 22
📦
isStudent = true
THREE WAYS TO DECLARE
var — Dart figures out the type
String / int — you say the type explicitly
final — set once, never changed again
const — fixed constant, known before running
// var — Dart guesses the type
var name = 'Aayush'; // String
var age = 22; // int
var gpa = 3.8; // double

// Explicit type — clearer, safer
String city = 'Kathmandu';
int score = 100;
bool isStudent = true;

// final — you get it once, it stays
final country = 'Nepal';

// const — pure fixed constant
const maxStudents = 10;
const pi = 3.14159;
Topic 1 · Variables

final vs const — simply explained

Both mean the value cannot change. The only difference is when the value is decided.

final

The value is decided when the app runs — but once set, you can never change it.

// App runs → you log in → name is set
final username = getUserInput();

// These are also fine with final:
final greeting = 'Hello';
final score = 95;

// Cannot change it after
// username = 'other'; → ERROR
🎓

Like your final exam grade — the teacher gives it to you when results are out. Once written, it never changes.

const

The value must be known before the app even starts. Pure fixed numbers or text only.

// These are fixed forever — use const
const maxStudents = 10;
const appName = 'Saarathi';
const pi = 3.14159;

// Can't use const if it needs the app
// to run first to figure out the value
// const score = getUserScore(); → ERROR
// Use final instead for that
📅

Like the number of days in a week — always 7, forever, decided before anything. That's a const.

📌 Simple rule: use final almost everywhere. Use const only for fixed values like limits, names, math constants.

Topic 2 · Data Types

Dart Data Types

Every variable has a type — the kind of data it holds.

STRING — text
String name = 'Nepal';
String msg = 'Hi $name';
INT & DOUBLE — numbers
int age = 22;
double price = 250.50;
BOOL — true or false
bool isLogin = true;
bool isAdult = age >= 18;
LIST — ordered collection
List<String> apps = [
  'eSewa', 'Khalti',
];
apps[0]; // 'eSewa'
MAP — key → value pairs
Map<String,int> scores = {
  'Maths': 95,
  'Science': 88,
};
SET — no duplicates
Set<String> tags = {
  'flutter', 'dart',
};
// adds already-there → ignored

List uses [ ] — Map uses { key: value } — Set uses { value }

Topic 2 · Built-in Methods

List & Map — Built-in Power

LIST METHODS
var apps = ['eSewa', 'Khalti', 'Fonepay'];

apps.add('IME Pay'); // add to end
apps.remove('Fonepay'); // remove item
apps.contains('Khalti'); // true
apps.length; // 3
apps.isEmpty; // false
apps.first; // 'eSewa'
apps.last; // 'IME Pay'
apps.reversed; // (IME Pay, Khalti, eSewa)

// Transform
apps.map((a) => a.toUpperCase());
apps.where((a) => a.length > 5);
apps.forEach((a) => print(a));

// Sort
apps.sort(); // alphabetical
MAP METHODS
var prices = {
  'momo': 120,
  'chowmein': 100,
  'dal bhat': 150,
};

prices['momo']; // 120
prices['samosa'] = 60; // add new
prices.remove('chowmein'); // remove

prices.keys; // (momo, dal bhat, samosa)
prices.values; // (120, 150, 60)
prices.containsKey('momo'); // true
prices.length; // 3

// Loop through
prices.forEach((item, price) {
  print('$item: Rs.$price');
});

📌 .map() transforms items · .where() filters items · .forEach() loops without creating a new list

Topic 2 · Strings

String Operations & Interpolation

Strings are text. Dart makes working with them easy and readable.

STRING INTERPOLATION — embed values
var name = 'Aayush';
var age = 22;

// Old way (ugly)
'Hello ' + name + ', age ' + age.toString()

// Dart way (clean)
'Hello $name, age $age'

// Expression in string → use ${}
'In 5 years: ${age + 5}'
'${name.toUpperCase()}'
MULTILINE STRINGS
var bio = '''
My name is Aayush.
I live in Kathmandu.
I love Flutter.
''';
COMMON STRING METHODS
var city = ' Kathmandu ';

city.trim(); // 'Kathmandu'
city.toUpperCase(); // 'KATHMANDU'
city.toLowerCase(); // 'kathmandu'
city.length; // 11 (with spaces)

var msg = 'Hello Flutter';
msg.contains('Flutter'); // true
msg.startsWith('Hello');// true
msg.split(' '); // ['Hello','Flutter']
msg.replaceAll('Flutter','Dart');
// 'Hello Dart'
Topic 3 · Null Safety

Null Safety — No Empty Surprises

Dart's way of making sure your app never crashes from an empty variable.

📭
The problem: empty box crash

Imagine you ask "what's in the mailbox?" — and there IS no mailbox. Your app crashes. Null means "nothing is there".

DART SOLUTION — two kinds of variables
String name = 'Aayush';
📦 Guaranteed to have something — no ?
String? middleName = null;
📭 Might be empty — the ? means "could be null"
// Non-nullable — must always have value
String name = 'Aayush';
// name = null; ← Dart blocks this

// Nullable — add ? to allow null
String? middleName = null;

// Always check before using nullable
if (middleName != null) {
  print(middleName);
}

// Shortcut: ?? gives a default value
var display = middleName ?? 'No middle name';
// if middleName is null → 'No middle name'

Memory trick: No ? = box is always full. Add ? = box might be empty (handle it).

🎮 Quiz 1 · Variables & Types

Test your understanding

3 quick questions on what we just covered. Think carefully before clicking.

Q1: What's the difference between final and const?
A
final is decided at runtime, const at compile time
B
They're exactly the same
C
const can be changed later
Correct! final gets its value when the app runs. const must be known before the app starts. Neither can change after.
Q2: What does String? mean?
A
String is optional to declare
B
String might be null
C
String is required
Correct! The ? means the variable can hold a String OR null. Without ?, it must always have a value.
Q3: What does ?? do?
A
Throws an error
B
Checks equality
C
Gives a default if null
Correct! ?? is the "if-null" operator. If the left side is null, use the right side as a fallback.
Topic 4 · Operators & Comments

Operators & Comments

ARITHMETIC & ASSIGNMENT
int a = 10, b = 3;
a + b // 13 add
a - b // 7 subtract
a * b // 30 multiply
a / b // 3.33 divide → double
a ~/ b // 3 integer divide
a % b // 1 remainder

var x = 10;
x += 5; // x = 15
x -= 3; // x = 12
x++; // x = 13 (add 1)
x--; // x = 12 (minus 1)
COMPARISON & LOGICAL
5 == 5 // true equal
5 != 3 // true not equal
10 > 5 // true greater
3 <= 3 // true less or equal

true && true // true AND (both)
true || false // true OR (either)
!true // false NOT (flip)

// Null-aware
name ?? 'default' // if null → default
user?.name // safe access
COMMENTS — notes in code
// Single line — for quick notes

/* Block comment
   spans lines */

/// Doc comment — IDE shows this
/// as a tooltip when you hover
void login() { }
Topic 5 · Control Flow

if / else — Making Decisions

🚦
Like a traffic light

Red → stop. Green → go. Yellow → slow. Code makes the same kind of branching decisions.

int age = 20;

if (age >= 18) {
  print('You can vote!');
} else {
  print('Too young to vote');
}

// else-if chain
int score = 75;
if (score >= 90) {
  print('Distinction');
} else if (score >= 60) {
  print('Pass');
} else {
  print('Keep trying');
}
TERNARY — one-line if/else
// condition ? if true : if false
var result = score >= 60
  ? 'Passed'
  : 'Failed';

// Nepali example
var greeting = age >= 18
  ? 'Namaste dai!'
  : 'Namaste bhai!';

📌 Use if/else for multi-line logic. Use the ternary for quick one-liner assignments.

Topic 5 · Control Flow

Loops — Repeat Actions

FOR LOOP — know how many times
// Print 0 to 4
for (var i = 0; i < 5; i++) {
  print(i); // 0, 1, 2, 3, 4
}
FOR-IN — loop through a list
var apps = ['eSewa', 'Khalti', 'FonePay'];
for (var app in apps) {
  print('I use $app');
}
WHILE LOOP — keep going until...
var count = 3;
while (count > 0) {
  print('$count...');
  count--;
}
print('Go!');
BREAK & CONTINUE
// break — stop the loop entirely
for (var i = 0; i < 10; i++) {
  if (i == 5) break;
  print(i); // 0,1,2,3,4
}

// continue — skip this iteration
for (var i = 0; i < 4; i++) {
  if (i == 2) continue;
  print(i); // 0, 1, 3
}
🎮 Quiz 2 · Operators & Control Flow

Test your logic skills

3 more questions. Think carefully before clicking.

Q1: What does ~/ do?
A
Regular division
B
Integer division (no decimals)
C
Modulo (remainder)
Correct! ~/ divides and drops the decimal. 10 ~/ 3 = 3, not 3.33.
var x = null;
print(x ?? 'hello');
What prints?
A
null
B
hello
C
Error
hello! x is null, so ?? kicks in and uses 'hello' as the fallback.
for (var i = 0; i < 3; i++) {
  print(i);
}
How many times does this loop run?
A
2 times
B
3 times
C
4 times
3 times! i starts at 0, runs while i < 3. So: i=0, i=1, i=2. Three iterations.
Topic 6 · Functions

Functions — Reusable Recipes

🍳
A function = a cooking recipe

Ingredients = parameters in. Steps = code inside. Dish = return value out.

VOID — NO RETURN VALUE
// void = does something, returns nothing
void greet(String name) {
  print('Hello $name!');
}

greet('Aayush'); // Hello Aayush!
greet('Sita'); // Hello Sita!
WITH RETURN TYPE
// int return — gives a number back
int add(int a, int b) {
  return a + b;
}

// String return — gives text back
String getGrade(int score) {
  if (score >= 90) return 'A';
  if (score >= 75) return 'B';
  return 'C';
}

var sum = add(3, 7); // 10
var g = getGrade(85); // 'B'

📌 Rule: if you write void, don't return anything. If you write int/String, you must return that type.

Topic 6 · Functions

Named Params & Arrow Functions

NAMED PARAMETERS — more readable
void createUser({
  required String name,
  int age = 18, // default value
}) {
  print('$name is $age');
}

// Call with names — very clear!
createUser(name: 'Aayush', age: 22);
createUser(name: 'Sita'); // age=18

required means you must pass it. Without required, a default value is used.

ARROW FUNCTION — one-liner shortcut
// Long way
int square(int n) {
  return n * n;
}

// Same, but shorter with =>
int square(int n) => n * n;

// More examples
String hello(String s) => 'Hi $s!';
bool isAdult(int age) => age >= 18;

print(square(4)); // 16
print(hello('Ram')); // Hi Ram!

📌 Use => when your function body is a single expression. It automatically returns the result.

🎮 Quiz 3 · Functions

Test your function knowledge

Final 3 questions. You've got this!

Q1: What does void mean?
A
Returns nothing
B
Returns null
C
The function is empty
Correct! void means the function does something but doesn't give back a value. Like pressing a button on a TV remote.
Q2: What does => do?
A
Compares two values
B
Shortcut for return
C
Points to a variable
Correct! => is shorthand for { return ... }. Use it when the function body is a single expression.
Q3: What's wrong with this code?
int add(int a, int b) {
  print(a + b);
}
A
Nothing wrong
B
Missing return statement
C
Wrong parameter types
Correct! It says it returns int, but only prints. It needs: return a + b; Or change int to void.
Topic 7 · Classes & Objects

Classes — Blueprints for Objects

🏠
Blueprint → House

Class = blueprint on paper. Object = the actual house built from it. One blueprint → many houses, all different families.

📋
CLASS
template
📱
OBJECT
instance
Student class → aayush, sita, ram (all different objects)

📌 A class defines what something has (properties) and how to create it (constructor).

class Student {
  // Properties — what it HAS
  String name;
  int age;

  // Constructor — how to BUILD it
  Student(this.name, this.age);
}

// Create objects from the blueprint
var s1 = Student('Aayush', 22);
var s2 = Student('Sita', 20);
var s3 = Student('Ram', 21);

// Access properties with dot (.)
print(s1.name); // Aayush
print(s2.age); // 20
Topic 7 · Classes & Objects

Adding Methods to Classes

Methods are functions that belong to a class — things an object can do.

class Student {
  String name;
  int age;

  Student(this.name, this.age);

  // Method — what it can DO
  void greet() {
    print('Hi, I am $name!');
  }

  // Getter — computed property
  bool get isAdult => age >= 18;
}
// Create & use objects
var s1 = Student('Aayush', 22);
var s2 = Student('Sita', 16);

s1.greet(); // Hi, I am Aayush!
s2.greet(); // Hi, I am Sita!

print(s1.isAdult); // true (22 >= 18)
print(s2.isAdult); // false (16 < 18)
KEY TERMS
Properties — data the object holds (name, age)
Methods — functions inside the class (greet)
Constructor — how you create an instance
Getter — computed value, accessed like a property
Topic 6 · Class Modifiers

Class Modifiers — Rules for Your Blueprints

Dart 3 lets you control how others can use your classes. Think of it as setting rules on your blueprint.

🏗️
Think of it like house blueprints

Imagine you built a house blueprint. Class modifiers let you say: "You can look at this but not copy it" or "You can only build exactly this, no changes."

abstract

Can't build directly — only a plan

abstract class Shape {
  double area();
}

Use when: You want a base class that forces children to implement methods

base

Extend ✅ Implement ❌

base class Animal {
  void breathe() {}
}

Use when: You want others to extend your class but keep your internal implementation

interface

Implement ✅ Extend ❌

interface class Logger {
  void log(String msg);
}

Use when: You want a contract — "promise to have these methods"

final

No extend, no implement — locked

final class Config {
  String apiKey;
}

Use when: Your class should never be changed or subclassed

sealed

Limited family — compiler checks all cases

sealed class Payment {}
class Cash extends Payment {}
class Card extends Payment {}

Use when: You want a fixed set of types (great with switch)

mixin

Share behavior without inheritance

mixin Swimmable {
  void swim() => print('Swimming!');
}

Use when: Multiple classes need the same ability

📌 Start simple: use final for most classes. Add abstract when you need a base class. You'll use sealed a lot with Flutter state management.

🎮 Game · Shopping Cart

Build a Shopping Cart in Dart

Add items, see totals update. Uses everything you learned: List, Map, class, methods, loops.

MENU
🍜 Momo — Rs.120
🍛 Chowmein — Rs.100
🍲 Dal Bhat — Rs.150
🥩 Samosa — Rs.60
☕ Tea — Rs.30
🥤 Lassi — Rs.50
Total: Rs.0
DART CLASS BEHIND IT
class CartItem {
  final String name;
  final int price;
  int quantity;
  CartItem(this.name, this.price)
    : quantity = 1;
}

class ShoppingCart {
  List<CartItem> items = [];
  bool studentDiscount = false;

  void addItem(String name, int price) {
    // adds or increments quantity
  }

  int get total {
    var sum = 0;
    for (var item in items) {
      sum += item.price * item.quantity;
    }
    if (studentDiscount)
      sum = (sum * 0.9).round();
    return sum;
  }
}
CART OUTPUT
// Cart is empty
// Add items to see output here
🎮 Mini Project · Student Report Card

Build a Report Card — click each feature

Every feature shows the Dart code + which concepts it uses. All of today's topics in one project!

📋 Student class
➕ Add marks
📊 Average
🎯 Grade
🖨 Report
CONCEPTS USED
🎮 Number Guesser — Dart in Action

All your Dart skills in one game

The phone UI is just a preview of what's coming with Flutter. Try to guess the number!

Number Guesser
Guess 1 – 10
Between 1 and 10

Attempts: 0
THE DART LOGIC BEHIND IT
import 'dart:math';

class GuesserGame {
  // Variables + Types
  final int secret;
  int attempts = 0;

  // Constructor
  GuesserGame()
    : secret = Random().nextInt(10) + 1;

  // Function + if/else
  String guess(int n) {
    attempts++;
    if (n == secret) return 'Correct!';
    if ((n - secret).abs() == 1) return 'Very close!';
    if (n > secret) return 'Too high!';
    return 'Too low!';
  }
}
CONCEPTS USED IN THIS GAME
✅ Variables (int, String)
✅ Classes + Constructor
✅ Functions + Return type
✅ if/else branching
✅ Operators (++, -, abs)
✅ final vs mutable var
Day 2 · Wrap up

What you learned today

Every concept here is a building block. Flutter uses all of them — starting next week.

📦

Variables & Null

var, final, const · String? · ??

🏷️

Types & Built-in Methods

String, int, bool, List, Map · .map() .where() .forEach()

💬

Strings & Interpolation

$var, ${expr}, trim, split, contains

⚙️

Operators

Arithmetic, comparison, logical, null-aware ??

🔀

Control Flow & Loops

if/else, ternary, for, while, break, continue

🔧

Functions

void, return, named params, arrow =>

🏗️

Classes & Objects

Blueprint, constructor, methods, getter

🔐

Class Modifiers

abstract, base, final, sealed, interface, mixin

NEXT CLASS
OOP — Inheritance, Mixins & More
BEFORE NEXT CLASS
dart.dev → Classes & OOP sections
🙋

Any Questions?

No question is too basic. If you're confused, someone else is too — ask now.

Practice on dartpad.dev — try the Student Report Card yourself!