DART PROGRAMMING COURSE · BRAINBIT INFOTECH

Part 1
Foundations

Module 1: Welcome to Dart

What Dart is, where it runs, your first programs · 4 h

Module 2: Variables, Types and Constants

Store data in named boxes: int, double, String, bool, var, final, const · 5 h

Module 3: Operators and Numbers

Arithmetic, comparison, logic, assignment and the math library · 5 h

Module 4: Strings and Text

Work with names, messages, emails and codes · 5 h

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

MODULE 1 · PART 1

Welcome to Dart

What Dart is, where it runs, your first programs
You will learn
  • What Dart is and why companies use it
  • Where Dart programs run (phone, web, server, laptop)
  • The shape of every Dart program: main(), statements and semicolons
  • Show output with print() and write notes with comments
  • Run Dart on your computer or in the browser (DartPad)
  • Read an error message calmly and fix it
You will build: a welcome banner, a visiting card and a shop receipt printed by code
4 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
🎯

Where is this used in real apps?

Dart is a modern, friendly language made by Google. It is the language behind Flutter, so one skill gives you Android, iPhone, web and desktop apps. It also writes servers and command-line tools.

Flutter mobile apps

Zomato-style food apps, banking apps, school apps: the screens are Flutter, the logic is Dart.

Servers and APIs

Dart can answer requests from an app, read a database and send JSON back.

Command-line tools

Small programs that rename 500 files, make reports or check marks sheets in seconds.

BrainBit Infotech Learning
🎓
Dart for Beginners
20 modules
Start
📱
Flutter Apps
Built with Dart
Open
💻
Practice Lab
200 examples
Run
🏆
Certificate
After capstone
Get

Your first Dart program

Every Dart program starts at main(). Think of it as the front door: Dart enters here and runs the lines inside the curly brackets { } from top to bottom. print() shows text in the output.

Tip: Text goes inside quotes. Every instruction ends with a semicolon ;. Press Run again to run it again.
void main() {
  print('Namaste, Ranchi!');
  print('Welcome to Dart.');
}

Statements, semicolons and comments

A statement is one instruction and ends with ;. A comment is a note for humans: Dart ignores it. Use // for one line and /* ... */ for many lines.

Real use: teams write comments to explain why the code exists, and to switch a line off while testing.
void main() {
  // This line is a comment. Dart ignores it.
  print('Line 1'); // a note can sit after code
  /* Many-line comment:
     print('Line 2');  <- this does NOT run */
  print('Line 3');
}

Printing numbers, maths and text

print() can show numbers, results of calculations and text. Use \n for a new line and \t for a tab space. Inside text, ${ } puts a calculation into the sentence.

Notice: 10 / 4 prints 2.5 and 2 + 3 prints 5. Dart keeps whole numbers and decimals apart; Module 3 explains this fully.
void main() {
  print(2 + 3);
  print(10 / 4);
  print('Fee for 3 months = Rs ${3 * 1500}');
  print('Line one\nLine two');
  print('Name:\tAsha');
}

Where do Dart programs run?

Dart can be prepared in three ways, so the same language reaches many devices.

Dart VM (while developing)

Runs your code instantly. Flutter "hot reload" uses this: change code, see the result in a second.

Native machine code (release)

AOT compile: the app becomes fast native code for Android, iPhone, Windows, Mac and Linux.

JavaScript (web)

Dart can be turned into JavaScript so your app runs in Chrome, Edge and Firefox.

Remember: you write Dart once; the Dart tools prepare it for each place.

Install Dart and run a program

You have two choices. Choice 1 needs no installation: open dartpad.dev in a browser, paste code and press Run. Choice 2 is the real setup on your computer. Copy these commands into Command Prompt or PowerShell:

Windows tip: install Dart from dart.dev/get-dart, or install Flutter (it includes Dart). Use VS Code with the free Dart extension.
# 1. Check Dart is installed
dart --version

# 2. Make a new console project
dart create hello_dart
cd hello_dart

# 3. Run it
dart run

# 4. Run any single file
dart run bin/hello_dart.dart

Reading error messages

Errors are normal, even for experts. Dart tells you the file, the line number and a short message. Read the first message only: later ones are often caused by the first.

Three steps: 1) read the line number, 2) look at that line and the one above it, 3) fix one error and run again. This slide does not run because Dart refuses to start code with a syntax error.
void main() {
  print('Hello')      // <- forgot the semicolon
  print('World');
}
// Dart stops before running anything and points at
// the end of line 2. Fix: add ; after print('Hello')

Animated explainer: From file to output

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

Animated explainer: Anatomy of main()

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

Namaste print

print() shows text in the output. Developers use it every day to see what a program is doing.
void main() {
  print('Namaste, Ranchi!');
  print('Welcome to BrainBit Infotech.');
  print('Let us learn Dart.');
}
Try it yourself: Print your name and your school or college on two lines.
Add print('your text'); lines inside main().
EASYReal project: digital visiting card screenExample 2 of 10

Visiting card

Many small print() lines make a card. Text in quotes is printed exactly as written.
void main() {
  print('------------------------');
  print('Name   : Asha Kumari');
  print('Role   : Student');
  print('City   : Ranchi, Jharkhand');
  print('Phone  : 98XXXXXX10');
  print('------------------------');
}
Try it yourself: Make a card for your best friend with a different city, such as Patna or Dhanbad.
Copy the program and change the text inside the quotes.
EASYReal project: fee and total calculationExample 3 of 10

Maths with print

Dart can calculate inside print(). Notice that / gives a decimal answer.
void main() {
  print(1500 + 250);
  print(12 * 5);
  print(100 - 35);
  print(100 / 4);
  print(7 + 3 * 2);
}
Try it yourself: Print the cost of 7 notebooks at Rs 45 each.
print(7 * 45);
EASYReal project: documenting code in a teamExample 4 of 10

Comments at work

Lines starting with // are notes. The commented-out line does not run, so it is a safe way to switch code off.
void main() {
  // Print the shop name
  print('Maa Durga Stores');
  // print('This line is switched off');
  print('Open 9 AM to 9 PM'); // timing
}
Try it yourself: Switch off the last print by putting // in front of it, then run.
Add // at the very start of the line.
EASYReal project: messages with special charactersExample 5 of 10

Quotes and new lines

Use \n for a new line and \t for a tab. A backslash before a quote lets the quote appear inside text.
void main() {
  print('Dear Student,\nWelcome to class.');
  print('Subject:\tDart');
  print('It\'s a great day in Ranchi!');
  print("He said: \"Study daily\"");
}
Try it yourself: Print a two-line Diwali greeting using one print() and \n.
print('Happy Diwali\nStay safe');
MEDIUMReal project: billing screen of a kirana shop appExample 6 of 10

Shop receipt

${ } puts a calculation inside text. The shop owner does not type totals by hand; the program calculates them.
void main() {
  print('===== Sharma General Store =====');
  print('Rice 5 kg x Rs 60  = Rs ${5 * 60}');
  print('Dal 2 kg x Rs 120  = Rs ${2 * 120}');
  print('Soap 3 pcs x Rs 38 = Rs ${3 * 38}');
  print('--------------------------------');
  print('TOTAL              = Rs ${5 * 60 + 2 * 120 + 3 * 38}');
}
Try it yourself: Add one more item (sugar 1 kg at Rs 44) and include it in the total.
Add a new print line and + 1 * 44 inside the TOTAL calculation.
MEDIUMReal project: drawing borders and banners in console toolsExample 7 of 10

Pattern with repeated text

A text times a number repeats it. '*' * 5 gives five stars. Programs use this to draw lines and borders.
void main() {
  print('*');
  print('*' * 2);
  print('*' * 3);
  print('*' * 4);
  print('=' * 20);
  print('DART COURSE');
  print('=' * 20);
}
Try it yourself: Print a triangle with 5 rows.
Add print('*' * 5); as a new line.
MEDIUMReal project: splitting a program into small reusable partsExample 8 of 10

A function called from main

A function is a named block of code. main() calls printLine() three times. Dart still starts at main(): the function runs only when it is called.
void printLine() {
  print('-' * 25);
}

void main() {
  printLine();
  print('Attendance Report');
  printLine();
  print('Present: 48');
  print('Absent : 2');
  printLine();
}
Try it yourself: Make a second function called printTitle that prints your school name, and call it from main().
void printTitle() { print('Your school'); } then call printTitle(); in main().
HARDReal project: school result sheet generatorExample 9 of 10

Report card printer

This combines everything: multi-line text with ''', repeated characters, and calculations inside text. Real report software builds sheets like this.
void main() {
  print('=' * 32);
  print('  RANCHI PUBLIC SCHOOL - REPORT');
  print('=' * 32);
  print('''Student : Rohit Kumar
Class   : 8-B''');
  print('Maths   : ${78}');
  print('Science : ${84}');
  print('English : ${69}');
  print('-' * 32);
  print('Total   : ${78 + 84 + 69} / 300');
  print('Percent : ${(78 + 84 + 69) / 300 * 100} %');
}
Try it yourself: Add one more subject (Hindi, 91 marks) and update the total and percentage out of 400.
Add a Hindi line, add + 91 to the sums, and divide by 400.
HARDReal project: maths and science calculationsExample 10 of 10

Using a library with import

Dart ships with libraries. import goes at the very top of the file. Here dart:math gives sqrt, pi and max. Notice 12.0: square root always gives a decimal number.
import 'dart:math';

void main() {
  print('Square root of 144 = ${sqrt(144)}');
  print('Value of pi        = $pi');
  double r = 7;
  print('Area of circle r=7 = ${pi * r * r}');
  print('Bigger of 40, 65   = ${max(40, 65)}');
}
Try it yourself: Find the area of a circle with radius 10.
Change double r = 7; to double r = 10;

Quick quiz

3 questions. Click an answer.
Which function does Dart run first?
start()main()run()print()
What does // do in Dart code?
Starts a commentPrints a lineDivides numbersStops the program
What must usually end an instruction in Dart?
A commaA colonA semicolon ;A full stop
Score: 0 / 3

Recap: what you learned in Module 1

Dart language

Made by Google. Powers Flutter apps, servers and command-line tools.

main() entry

Every program starts at main(). Lines inside { } run top to bottom.

print()

Shows text, numbers and calculation results in the output.

Semicolons

Each statement ends with ;. A missing one is the most common first error.

Comments

// for one line, /* */ for many lines. Dart ignores them.

Run it

dart run on your computer, or paste code into dartpad.dev.

Next: Variables, Types and Constants - Store data in named boxes: int, double, String, bool, var, final, const
MODULE 2 · PART 1

Variables, Types and Constants

Store data in named boxes: int, double, String, bool, var, final, const
You will learn
  • What a variable is and how to name it
  • int, double, String, bool and var
  • Type inference and changing values
  • final and const: values that never change
  • Converting between types (int, double, String)
  • Using $ and ${ } to build sentences
You will build: a student profile, a fee calculator and a temperature converter
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
📦

Where is this used in real apps?

Every app remembers things: a name, a price, a score. A variable is a labelled box in the computer memory that holds one value so you can use it again later.

Shopping apps

The price, quantity and discount are variables. The bill is calculated from them.

School apps

Name, roll number, marks and attendance are all stored in variables.

Games

Score, lives and level are variables that change while you play.

My Profile
👤
Name: Asha Kumari
String
🎂
Age: 16
int
📏
Height: 5.4 ft
double
✅
Admitted: true
bool

Making a variable

Write the type, a name, = and a value. The name lets you use the value again. Names start with a letter, have no spaces and are written in camelCase: studentName.

Types: int whole numbers, double decimals, String text, bool true or false.
void main() {
  int age = 17;
  String name = 'Asha';
  double height = 5.4;
  bool isStudent = true;
  print(name);
  print(age);
  print(height);
  print(isStudent);
}

Changing a variable

A variable can get a new value later with =. The old value is replaced. Shortcuts: score += 5 means score = score + 5.

Real use: a game score goes up every time you win a point.
void main() {
  int score = 10;
  print(score);
  score = 15;
  print(score);
  score += 5;
  print(score);
  score++;
  print(score);
}

var and type inference

var lets Dart guess the type from the value. After that the type is fixed: a variable made with a number cannot later hold text.

Tip: use var when the value makes the type obvious; write the type when it helps readers.
void main() {
  var city = 'Ranchi';
  var pin = 834001;
  var rate = 8.5;
  print(city.runtimeType);
  print(pin.runtimeType);
  print(rate.runtimeType);
  city = 'Patna';
  print(city);
}

final and const

final: set once, never changed (value can be decided while the program runs). const: fixed before the program even runs. Use them for things like GST rate or the school name.

Rule: if a value never changes, make it final or const. This prevents bugs.
void main() {
  const double gst = 0.18;
  final DateTime now = DateTime.now();
  double price = 1000;
  print('GST = ${price * gst}');
  print(now.year > 2000);
  // gst = 0.12;   // ERROR: cannot change a const
}

Converting types

Text and numbers are different. Use int.parse() and double.parse() to turn text into numbers, and .toString(), .toInt(), .toDouble() to convert numbers.

Real use: text typed by a user is always text. Convert it before doing maths.
void main() {
  String text = '45';
  int n = int.parse(text);
  print(n + 5);
  double d = double.parse('2.5');
  print(d * 2);
  print(7.9.toInt());
  print(3.toDouble());
  print(100.toString() + ' rupees');
}

Text with $ and ${ }

String interpolation puts values inside sentences. Use $name for a simple variable and ${ expression } for anything bigger.

Compare: 'Hello ' + name works too, but interpolation is shorter and clearer.
void main() {
  String name = 'Rohit';
  int marks = 82;
  print('Hello $name');
  print('$name scored $marks marks');
  print('Next year: ${marks + 5}');
  print('Upper: ${name.toUpperCase()}');
}

Animated explainer: A variable is a labelled box

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

Animated explainer: The four main types

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

Student profile

Four variables of four types are stored and printed. Using variables means you change the value in one place only.
void main() {
  String name = 'Asha Kumari';
  int age = 16;
  double height = 5.4;
  bool isPresent = true;
  print('Name    : $name');
  print('Age     : $age');
  print('Height  : $height ft');
  print('Present : $isPresent');
}
Try it yourself: Change the details to your own and add a city variable.
Add String city = 'Ranchi'; and print it.
EASYReal project: sorting and rearranging dataExample 2 of 10

Swap two values

To swap you need a third helper variable, like using a third glass to swap water between two glasses.
void main() {
  int a = 10;
  int b = 20;
  print('Before: a=$a b=$b');
  int temp = a;
  a = b;
  b = temp;
  print('After : a=$a b=$b');
}
Try it yourself: Swap two names (Strings) in the same way.
Use String x = 'Amit'; String y = 'Sita'; and a temp variable.
EASYReal project: floor and land measurementExample 3 of 10

Rectangle area

Area = length x breadth. The result is stored in a variable too, so it can be reused.
void main() {
  int length = 12;
  int breadth = 8;
  int area = length * breadth;
  int perimeter = 2 * (length + breadth);
  print('Area      = $area sq ft');
  print('Perimeter = $perimeter ft');
}
Try it yourself: Find the area of a room 15 x 11 feet.
Change length and breadth.
EASYReal project: weather app: Celsius to FahrenheitExample 4 of 10

Temperature converter

Formula F = C x 9 / 5 + 32. Note that / always gives a double.
void main() {
  double celsius = 36.5;
  double fahrenheit = celsius * 9 / 5 + 32;
  print('$celsius C = $fahrenheit F');
  double ranchi = 28;
  print('$ranchi C = ${ranchi * 9 / 5 + 32} F');
}
Try it yourself: Convert 100 C (boiling water) to F.
Set celsius to 100.
EASYReal project: tax rate and constants in billing softwareExample 5 of 10

Final and const

GST rate never changes during a bill, so it is a const. The program calculates GST and the final price from it.
void main() {
  const double gstRate = 0.18;
  final double price = 2500;
  double gst = price * gstRate;
  double total = price + gst;
  print('Price : Rs $price');
  print('GST   : Rs $gst');
  print('Total : Rs $total');
}
Try it yourself: Change the price to 4999 and see the new total.
Change the number in final double price = ...;
MEDIUMReal project: reading numbers typed by a userExample 6 of 10

Parse text to numbers

Form fields give you text. int.parse and double.parse convert so you can add them.
void main() {
  String qtyText = '12';
  String rateText = '45.5';
  int qty = int.parse(qtyText);
  double rate = double.parse(rateText);
  double total = qty * rate;
  print('Quantity: $qty');
  print('Rate    : $rate');
  print('Total   : Rs $total');
  print('Joined as text: ' + qtyText + rateText);
}
Try it yourself: Parse the texts '8' and '7' and print their sum.
print(int.parse('8') + int.parse('7'));
MEDIUMReal project: bank and loan calculatorsExample 7 of 10

Simple interest

SI = P x R x T / 100. Doubles and ints can mix; the result is a double.
void main() {
  double principal = 50000;
  double rate = 8.5;
  int years = 3;
  double interest = principal * rate * years / 100;
  double amount = principal + interest;
  print('Principal : Rs $principal');
  print('Interest  : Rs $interest');
  print('Amount    : Rs $amount');
}
Try it yourself: Find interest on Rs 1,20,000 at 7 percent for 2 years.
Change the three variables.
MEDIUMReal project: electricity department billingExample 8 of 10

Electricity bill

A fixed charge plus units x rate, then GST. Uses const for the rates so they are easy to find and change.
void main() {
  const double ratePerUnit = 6.5;
  const double fixedCharge = 120;
  int units = 230;
  double energy = units * ratePerUnit;
  double subtotal = energy + fixedCharge;
  double gst = subtotal * 0.05;
  print('Units used : $units');
  print('Energy     : Rs $energy');
  print('Fixed      : Rs $fixedCharge');
  print('Tax 5%     : Rs $gst');
  print('Payable    : Rs ${subtotal + gst}');
}
Try it yourself: Calculate the bill for 310 units.
Change the units variable.
HARDReal project: result software for a schoolExample 9 of 10

Marks sheet with percentage

Total, average and percentage are calculated from marks variables. toStringAsFixed(2) controls decimals.
void main() {
  String student = 'Rohit Kumar';
  int maths = 78, science = 84, english = 69, hindi = 91;
  int total = maths + science + english + hindi;
  double percent = total / 400 * 100;
  print('Student : $student');
  print('Total   : $total / 400');
  print('Percent : ${percent.toStringAsFixed(2)} %');
  print('Average : ${(total / 4).toStringAsFixed(1)}');
}
Try it yourself: Add a computer subject and recalculate out of 500.
Add the variable to total and use 500.
HARDReal project: loan EMI screen in a bank appExample 10 of 10

EMI planner

The EMI formula uses a power. Real banking apps do exactly this. pow comes from dart:math.
import 'dart:math';

void main() {
  double loan = 500000;
  double yearlyRate = 9;
  int months = 36;
  double r = yearlyRate / 12 / 100;
  double emi = loan * r * pow(1 + r, months) / (pow(1 + r, months) - 1);
  double totalPay = emi * months;
  print('Loan        : Rs $loan');
  print('Monthly EMI : Rs ${emi.toStringAsFixed(2)}');
  print('Total pay   : Rs ${totalPay.toStringAsFixed(2)}');
  print('Interest    : Rs ${(totalPay - loan).toStringAsFixed(2)}');
}
Try it yourself: Find the EMI for Rs 3,00,000 over 24 months at 10 percent.
Change loan, yearlyRate and months.

Quick quiz

3 questions. Click an answer.
Which type stores the value 49.5?
intdoubleboolString
Which keyword makes a value that can never change?
varintconstvoid
What does int.parse('25') return?
The text 25The number 25An errortrue
Score: 0 / 3

Recap: what you learned in Module 2

Variables

Named boxes that store data. Write the type, name and value.

Types

int whole, double decimal, String text, bool true or false.

var

Dart guesses the type, which then stays fixed.

final / const

Values that never change. Use them to avoid bugs.

Convert

int.parse, double.parse, toString, toInt, toDouble.

Interpolation

$name and ${ expression } build sentences.

Next: Operators and Numbers - Arithmetic, comparison, logic, assignment and the math library
MODULE 3 · PART 1

Operators and Numbers

Arithmetic, comparison, logic, assignment and the math library
You will learn
  • Arithmetic: + - * / ~/ %
  • Integer and decimal division (/ , ~/ , %)
  • Comparison operators that give true or false
  • Logical operators: && || !
  • Assignment shortcuts and ++ --
  • Operator precedence, ternary ?: and dart:math
You will build: a discount calculator, a change counter and an eligibility checker
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
➕

Where is this used in real apps?

Operators are the symbols that make the program calculate and decide: add prices, compare marks, check whether a user is eligible.

Billing

Totals, discounts and GST all use arithmetic operators.

Eligibility checks

Age >= 18 && hasId decides if a person can vote or apply.

Games

Score++, lives-- and comparisons decide who wins.

Discount Calculator
🛍
Price Rs 2,000
MRP
🏷
Discount 15%
Offer
💰
You pay Rs 1,700
Total

Arithmetic operators

+ add, - subtract, * multiply, / divide (always a decimal), ~/ whole-number divide, % remainder.

Remember: 17 divided by 5 is 3 remainder 2. So ~/ gives 3 and % gives 2.
void main() {
  print(17 + 5);
  print(17 - 5);
  print(17 * 5);
  print(17 / 5);
  print(17 ~/ 5);
  print(17 % 5);
}

Comparison operators

They compare two values and answer true or false: == equal, != not equal, >, <, >=, <=.

Careful: one = stores a value; two == compares.
void main() {
  int marks = 72;
  print(marks >= 33);
  print(marks == 100);
  print(marks != 72);
  print(marks > 80);
  print('abc' == 'abc');
}

Logical operators

&& (and): both must be true. || (or): at least one true. ! (not): flips true and false.

Real use: login checks: userOk && passwordOk.
void main() {
  int age = 19;
  bool hasId = true;
  print(age >= 18 && hasId);
  print(age < 18 || hasId);
  print(!hasId);
  bool canVote = age >= 18 && hasId;
  print('Can vote: $canVote');
}

Assignment and ++ --

+=, -=, *=, /=, ~/=, %= update a variable. ++ adds 1 and -- subtracts 1.

Real use: stock goes down with each sale: stock -= sold;
void main() {
  int stock = 100;
  stock -= 12;
  print(stock);
  stock *= 2;
  print(stock);
  stock++;
  print(stock);
  stock--;
  print(stock);
}

Ternary and null-aware

condition ? valueIfTrue : valueIfFalse is a one-line decision. ?? gives a fallback when a value is null.

Read it as: "Is marks at least 33? Yes: Pass. No: Fail."
void main() {
  int marks = 45;
  String result = marks >= 33 ? 'Pass' : 'Fail';
  print(result);
  String? nick;
  print(nick ?? 'No nickname');
  print(10 > 5 ? 'Big' : 'Small');
}

Precedence and dart:math

Multiplication happens before addition. Use brackets to be clear. import 'dart:math' gives sqrt, pow, min, max, pi.

Tip: when unsure, add brackets. They cost nothing and avoid bugs.
import 'dart:math';

void main() {
  print(2 + 3 * 4);
  print((2 + 3) * 4);
  print(pow(2, 10));
  print(sqrt(81));
  print(min(8, 3));
  print(max(8, 3));
  print(10.5.round());
  print(10.2.ceil());
  print(10.9.floor());
}

Animated explainer: Division: / vs ~/ vs %

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

Animated explainer: && needs both, || needs one

Press Next to walk through it step by step, or Auto play.
EASYReal project: cash counter at a shopExample 1 of 10

Change counter

Customer gives Rs 500 for a bill of Rs 347. Change = given - bill.
void main() {
  int bill = 347;
  int given = 500;
  int change = given - bill;
  print('Bill   : Rs $bill');
  print('Given  : Rs $given');
  print('Change : Rs $change');
}
Try it yourself: Bill Rs 1,285 and given Rs 2,000: find the change.
Change the two numbers.
EASYReal project: checking ticket and roll numbersExample 2 of 10

Even or odd

A number is even if the remainder after dividing by 2 is 0.
void main() {
  int n = 27;
  print('$n remainder 2 = ${n % 2}');
  print('Is even? ${n % 2 == 0}');
  print('Is even? ${48 % 2 == 0}');
}
Try it yourself: Test the number 1001.
Set n = 1001.
EASYReal project: result generationExample 3 of 10

Pass or fail

Comparison gives true or false; the ternary turns it into words.
void main() {
  int marks = 56;
  print('Passed? ${marks >= 33}');
  print(marks >= 33 ? 'Result: PASS' : 'Result: FAIL');
  print(marks >= 75 ? 'Distinction' : 'No distinction');
}
Try it yourself: Try marks 28 and marks 91.
Change marks.
EASYReal project: packing and boxing in a poultry businessExample 4 of 10

Packing eggs

~/ counts full trays and % counts leftover eggs. 30 eggs fit a tray.
void main() {
  int eggs = 245;
  int perTray = 30;
  print('Full trays : ${eggs ~/ perTray}');
  print('Left over  : ${eggs % perTray}');
}
Try it yourself: Pack 500 laddoos in boxes of 12.
Change the two variables.
EASYReal project: inventory countExample 5 of 10

Increase and decrease

++, --, += and -= update a stock count, as in an inventory app.
void main() {
  int stock = 50;
  stock += 20;
  print('After purchase: $stock');
  stock -= 8;
  print('After sale    : $stock');
  stock--;
  print('One damaged   : $stock');
}
Try it yourself: Add another sale of 15 items.
Add stock -= 15; and print it.
MEDIUMReal project: e-commerce checkoutExample 6 of 10

Discount and GST bill

Discount first, then GST on the reduced price. Order matters.
void main() {
  double mrp = 2400;
  double discountPct = 15;
  double discount = mrp * discountPct / 100;
  double afterDiscount = mrp - discount;
  double gst = afterDiscount * 18 / 100;
  double payable = afterDiscount + gst;
  print('MRP       : Rs $mrp');
  print('Discount  : Rs $discount');
  print('GST 18%   : Rs $gst');
  print('You pay   : Rs ${payable.toStringAsFixed(2)}');
}
Try it yourself: Recalculate with 25 percent discount.
Change discountPct.
MEDIUMReal project: government forms and loan screeningExample 7 of 10

Voting and loan eligibility

Logical operators join conditions. One false in && fails the whole check.
void main() {
  int age = 22;
  bool hasVoterId = true;
  double salary = 28000;
  print('Can vote : ${age >= 18 && hasVoterId}');
  print('Loan ok  : ${age >= 21 && age <= 58 && salary >= 25000}');
  print('Student concession: ${age < 18 || age > 60}');
}
Try it yourself: Set age to 17 and check all three lines.
Change age to 17.
MEDIUMReal project: timetables and video playersExample 8 of 10

Time converter

~/ and % turn seconds into hours, minutes and seconds.
void main() {
  int totalSeconds = 5025;
  int hours = totalSeconds ~/ 3600;
  int minutes = (totalSeconds % 3600) ~/ 60;
  int seconds = totalSeconds % 60;
  print('$totalSeconds s = ${hours}h ${minutes}m ${seconds}s');
}
Try it yourself: Convert 10000 seconds.
Change totalSeconds.
HARDReal project: ATM cash dispenser logicExample 9 of 10

Rupee notes counter

Greedy method: use the biggest note first with ~/, then continue with the % remainder.
void main() {
  int amount = 3870;
  int n500 = amount ~/ 500;
  amount = amount % 500;
  int n100 = amount ~/ 100;
  amount = amount % 100;
  int n50 = amount ~/ 50;
  amount = amount % 50;
  int n10 = amount ~/ 10;
  amount = amount % 10;
  print('500 x $n500');
  print('100 x $n100');
  print(' 50 x $n50');
  print(' 10 x $n10');
  print('Left: Rs $amount');
}
Try it yourself: Withdraw Rs 2,990 and check the notes.
Change the first amount.
HARDReal project: maps and delivery appsExample 10 of 10

Distance between two places

Pythagoras: distance = sqrt(dx*dx + dy*dy). sqrt and pow come from dart:math.
import 'dart:math';

void main() {
  double x1 = 2, y1 = 3;
  double x2 = 14, y2 = 12;
  double dx = x2 - x1;
  double dy = y2 - y1;
  double dist = sqrt(pow(dx, 2) + pow(dy, 2));
  print('dx=$dx dy=$dy');
  print('Distance = $dist km');
  print('Rounded  = ${dist.toStringAsFixed(1)} km');
  print('Delivery fee = Rs ${(dist * 8).round()}');
}
Try it yourself: Find the distance between (0,0) and (6,8).
Change the four coordinates.

Quick quiz

3 questions. Click an answer.
What does 17 % 5 give?
323.412
Which operator means "and" in Dart?
&&&and||
What is the result of 2 + 3 * 4?
2014249
Score: 0 / 3

Recap: what you learned in Module 3

Arithmetic

+ - * / ~/ %. Divide / always gives a decimal.

Compare

== != > < >= <= give true or false.

Logic

&& and, || or, ! not.

Shortcuts

+= -= ++ -- update variables.

Ternary

condition ? yes : no decides in one line.

dart:math

sqrt, pow, min, max, pi and rounding.

Next: Strings and Text - Work with names, messages, emails and codes
MODULE 4 · PART 1

Strings and Text

Work with names, messages, emails and codes
You will learn
  • Create strings with single, double and triple quotes
  • Join, repeat and insert values into text
  • Length, upper/lower case, trim and padding
  • Search, replace, split and join
  • Substring, characters and indexing
  • StringBuffer and comparing strings
You will build: a name formatter, an email checker and a simple password strength tester
5 class hours · 10 examples (5 Easy, 3 Medium, 2 Hard)
💬

Where is this used in real apps?

Names, messages, addresses and passwords are all text. Dart gives you many ready-made tools (methods) to clean, search and change text.

Sign-up forms

Trim spaces, make email lower case, check the length of a password.

Messaging apps

Search, replace and split text in chats and SMS.

Reports

Pad and align text so tables look neat in a printout.

Sign Up
✉
asha@example.com
valid email
🔑
********
strong password
👤
ASHA KUMARI
name formatted

Making strings

Use single ' ' or double " " quotes. Three quotes ''' ''' make a multi-line string. Prefix r gives a raw string where \ is just a character.

Tip: use double quotes when your text contains an apostrophe: "It's fine".
void main() {
  String a = 'Namaste';
  String b = "Ranchi";
  String c = '''Line 1
Line 2''';
  print(a + ' ' + b);
  print(c);
  print(r'C:\new\folder');
}

Length, case and trim

.length counts characters. .toUpperCase() and .toLowerCase() change case. .trim() removes spaces at both ends.

Real use: always .trim() user input before saving it.
void main() {
  String name = '  Asha Kumari  ';
  print(name.length);
  print(name.trim().length);
  print(name.trim().toUpperCase());
  print(name.trim().toLowerCase());
  print(name.isEmpty);
  print(''.isEmpty);
}

Search and replace

contains, startsWith, endsWith, indexOf search. replaceAll replaces text.

Note: indexOf returns -1 when the text is not found.
void main() {
  String s = 'Learn Dart in Ranchi';
  print(s.contains('Dart'));
  print(s.startsWith('Learn'));
  print(s.endsWith('Patna'));
  print(s.indexOf('Dart'));
  print(s.replaceAll('Ranchi', 'Bihar'));
}

Split and join

split cuts text into a list at a separator. join on a list joins pieces back into one text.

Real use: CSV files and SMS messages are split on commas or spaces.
void main() {
  String csv = 'Asha,Rohit,Meena';
  List<String> names = csv.split(',');
  print(names);
  print(names.length);
  print(names.join(' | '));
  print('one two three'.split(' ').length);
}

Substring and characters

Characters are counted from 0. s[0] is the first. substring(start, end) cuts a piece (end is not included).

Careful: asking for a position past the end causes a RangeError.
void main() {
  String s = 'BrainBit Infotech';
  print(s[0]);
  print(s[s.length - 1]);
  print(s.substring(0, 5));
  print(s.substring(5));
  for (var ch in s.split('')) {
    print(ch);
    break;
  }
}

Padding and StringBuffer

padLeft and padRight align text. StringBuffer builds a long text efficiently by adding pieces with write.

Real use: invoice numbers like INV-007 use padLeft.
void main() {
  print('7'.padLeft(3, '0'));
  print('Item'.padRight(10, '.') + '50');
  var sb = StringBuffer();
  sb.write('Hello');
  sb.write(' ');
  sb.writeln('Ranchi');
  sb.write('Done');
  print(sb.toString());
}

Animated explainer: Index positions of a string

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

Animated explainer: split then join

Press Next to walk through it step by step, or Auto play.
EASYReal project: form data cleaningExample 1 of 10

Name formatter

Users type spaces and mixed case. trim and toUpperCase clean the data before saving.
void main() {
  String raw = '   asha kumari   ';
  String clean = raw.trim();
  print('[$raw]');
  print('[$clean]');
  print(clean.toUpperCase());
  print('Length: ${clean.length}');
}
Try it yourself: Clean the text ' ranchi '.
Change raw.
EASYReal project: avatar circle in a profile screenExample 2 of 10

Initials maker

Take the first letter of the first and last name using [0].
void main() {
  String first = 'Rohit';
  String last = 'Kumar';
  String initials = first[0] + last[0];
  print(initials);
  print('Welcome, $first ${last.toUpperCase()}');
}
Try it yourself: Make initials for Asha Kumari.
Change first and last.
EASYReal project: search box in an appExample 3 of 10

Does it contain?

contains answers true or false. Convert both to lower case so the match ignores case.
void main() {
  String title = 'Learn Flutter in Ranchi';
  String search = 'flutter';
  print(title.contains(search));
  print(title.toLowerCase().contains(search));
}
Try it yourself: Search for 'RANCHI' in the title.
Use toLowerCase() on both.
EASYReal project: censoring and templatesExample 4 of 10

Replace words

replaceAll fills a message template.
void main() {
  String template = 'Dear NAME, your fee of AMOUNT is due.';
  String msg = template.replaceAll('NAME', 'Asha').replaceAll('AMOUNT', 'Rs 1500');
  print(msg);
}
Try it yourself: Add a DATE placeholder and replace it.
Add 'on DATE' and one more replaceAll.
EASYReal project: invoice numbersExample 5 of 10

Repeat and pad

padLeft adds leading zeros. Used for roll numbers, invoice numbers and token numbers.
void main() {
  for (int i = 1; i <= 3; i++) {
    print('INV-' + i.toString().padLeft(4, '0'));
  }
  print('=' * 12);
  print('Total'.padRight(8) + '500'.padLeft(4));
}
Try it yourself: Print roll numbers 1 to 3 as R-001.
Use padLeft(3, '0') and 'R-'.
MEDIUMReal project: sign-up form validationExample 6 of 10

Email checker

A very simple check: contains @ and ends with .com or .in. Real apps use RegExp (Module 17).
void main() {
  List<String> emails = ['asha@example.com', 'rohit.example.com', 'meena@site.in', 'bad@'];
  for (var e in emails) {
    bool ok = e.contains('@') && (e.endsWith('.com') || e.endsWith('.in'));
    print('${e.padRight(20)} -> ${ok ? 'valid' : 'invalid'}');
  }
}
Try it yourself: Add your own email to the list.
Add a string to the list.
MEDIUMReal project: security rules on a sign-up pageExample 7 of 10

Password strength

Check length, then look for a digit by testing each character. Combines String methods with logic.
void main() {
  String pw = 'Ranchi2026';
  bool longEnough = pw.length >= 8;
  bool hasDigit = pw.split('').any((c) => '0123456789'.contains(c));
  bool hasUpper = pw != pw.toLowerCase();
  print('Long enough: $longEnough');
  print('Has digit  : $hasDigit');
  print('Has capital: $hasUpper');
  print((longEnough && hasDigit && hasUpper) ? 'STRONG' : 'WEAK');
}
Try it yourself: Test the password 'abc'.
Change pw = 'abc';
MEDIUMReal project: blog editor and SMS limitExample 8 of 10

Word counter

Split on spaces to count words. SMS apps also count characters.
void main() {
  String text = 'Dart is easy to learn and fun to use';
  List<String> words = text.split(' ');
  print('Characters: ${text.length}');
  print('Words     : ${words.length}');
  print('First     : ${words.first}');
  print('Last      : ${words.last}');
  print('Longest   : ${(words..sort((a, b) => b.length.compareTo(a.length))).first}');
}
Try it yourself: Count the words in your own sentence.
Change text.
HARDReal project: puzzles, interviews and data checksExample 9 of 10

Palindrome checker

A palindrome reads the same backwards. Reverse by splitting, reversing the list and joining.
bool isPalindrome(String s) {
  String clean = s.toLowerCase().replaceAll(' ', '');
  String rev = clean.split('').reversed.join();
  return clean == rev;
}

void main() {
  for (var w in ['madam', 'Dart', 'nurses run', 'level']) {
    print('$w -> ${isPalindrome(w)}');
  }
}
Try it yourself: Test the word 'Malayalam'.
Add it to the list.
HARDReal project: POS billing machineExample 10 of 10

Receipt printer

Aligned columns using padRight, padLeft and StringBuffer. This is how thermal printers lay out a bill.
void main() {
  var items = [['Rice 5kg', 300], ['Dal 2kg', 240], ['Soap x3', 114]];
  var sb = StringBuffer();
  sb.writeln('SHARMA STORE, RANCHI');
  sb.writeln('=' * 24);
  int total = 0;
  for (var it in items) {
    sb.writeln((it[0] as String).padRight(14) + it[1].toString().padLeft(10));
    total += it[1] as int;
  }
  sb.writeln('-' * 24);
  sb.write('TOTAL'.padRight(14) + total.toString().padLeft(10));
  print(sb.toString());
}
Try it yourself: Add one more item and check the total.
Add ['Sugar 1kg', 44] to the items.

Quick quiz

3 questions. Click an answer.
What is 'Dart'[0]?
DaDartAn error
Which method removes spaces from both ends?
cut()trim()strip()clean()
What does 'a,b,c'.split(',').length give?
1350
Score: 0 / 3

Recap: what you learned in Module 4

Strings

Text in quotes. Triple quotes for many lines.

Basics

length, trim, toUpperCase, toLowerCase, isEmpty.

Search

contains, startsWith, endsWith, indexOf, replaceAll.

Split/join

split makes a list, join makes text.

Index

Start at 0. substring(start, end) excludes end.

Build

padLeft, padRight and StringBuffer make neat output.

Next: the next part of the course.

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