What Dart is, where it runs, your first programs · 4 h
Store data in named boxes: int, double, String, bool, var, final, const · 5 h
Arithmetic, comparison, logic, assignment and the math library · 5 h
Work with names, messages, emails and codes · 5 h
19 class hours · 40 practice examples · Trainer: Nandan Kumar, Ranchi
Zomato-style food apps, banking apps, school apps: the screens are Flutter, the logic is Dart.
Dart can answer requests from an app, read a database and send JSON back.
Small programs that rename 500 files, make reports or check marks sheets in seconds.
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.
;. Press Run again to run it again.void main() {
print('Namaste, Ranchi!');
print('Welcome to Dart.');
}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.
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');
}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.
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');
}Dart can be prepared in three ways, so the same language reaches many devices.
Runs your code instantly. Flutter "hot reload" uses this: change code, see the result in a second.
AOT compile: the app becomes fast native code for Android, iPhone, Windows, Mac and Linux.
Dart can be turned into JavaScript so your app runs in Chrome, Edge and Firefox.
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:
# 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
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.
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')void main() {
print('Namaste, Ranchi!');
print('Welcome to BrainBit Infotech.');
print('Let us learn Dart.');
}void main() {
print('------------------------');
print('Name : Asha Kumari');
print('Role : Student');
print('City : Ranchi, Jharkhand');
print('Phone : 98XXXXXX10');
print('------------------------');
}void main() {
print(1500 + 250);
print(12 * 5);
print(100 - 35);
print(100 / 4);
print(7 + 3 * 2);
}void main() {
// Print the shop name
print('Maa Durga Stores');
// print('This line is switched off');
print('Open 9 AM to 9 PM'); // timing
}void main() {
print('Dear Student,\nWelcome to class.');
print('Subject:\tDart');
print('It\'s a great day in Ranchi!');
print("He said: \"Study daily\"");
}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}');
}'*' * 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);
}void printLine() {
print('-' * 25);
}
void main() {
printLine();
print('Attendance Report');
printLine();
print('Present: 48');
print('Absent : 2');
printLine();
}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} %');
}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)}');
}Made by Google. Powers Flutter apps, servers and command-line tools.
Every program starts at main(). Lines inside { } run top to bottom.
Shows text, numbers and calculation results in the output.
Each statement ends with ;. A missing one is the most common first error.
// for one line, /* */ for many lines. Dart ignores them.
dart run on your computer, or paste code into dartpad.dev.
The price, quantity and discount are variables. The bill is calculated from them.
Name, roll number, marks and attendance are all stored in variables.
Score, lives and level are variables that change while you play.
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.
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);
}A variable can get a new value later with =. The old value is replaced. Shortcuts: score += 5 means score = score + 5.
void main() {
int score = 10;
print(score);
score = 15;
print(score);
score += 5;
print(score);
score++;
print(score);
}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.
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: 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.
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
}Text and numbers are different. Use int.parse() and double.parse() to turn text into numbers, and .toString(), .toInt(), .toDouble() to convert numbers.
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');
}String interpolation puts values inside sentences. Use $name for a simple variable and ${ expression } for anything bigger.
'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()}');
}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');
}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');
}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');
}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');
}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');
}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);
}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');
}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}');
}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)}');
}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)}');
}Named boxes that store data. Write the type, name and value.
int whole, double decimal, String text, bool true or false.
Dart guesses the type, which then stays fixed.
Values that never change. Use them to avoid bugs.
int.parse, double.parse, toString, toInt, toDouble.
$name and ${ expression } build sentences.
Totals, discounts and GST all use arithmetic operators.
Age >= 18 && hasId decides if a person can vote or apply.
Score++, lives-- and comparisons decide who wins.
+ add, - subtract, * multiply, / divide (always a decimal), ~/ whole-number divide, % remainder.
~/ 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);
}They compare two values and answer true or false: == equal, != not equal, >, <, >=, <=.
= 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');
}&& (and): both must be true. || (or): at least one true. ! (not): flips true and false.
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');
}+=, -=, *=, /=, ~/=, %= update a variable. ++ adds 1 and -- subtracts 1.
stock -= sold;void main() {
int stock = 100;
stock -= 12;
print(stock);
stock *= 2;
print(stock);
stock++;
print(stock);
stock--;
print(stock);
}condition ? valueIfTrue : valueIfFalse is a one-line decision. ?? gives a fallback when a value is null.
void main() {
int marks = 45;
String result = marks >= 33 ? 'Pass' : 'Fail';
print(result);
String? nick;
print(nick ?? 'No nickname');
print(10 > 5 ? 'Big' : 'Small');
}Multiplication happens before addition. Use brackets to be clear. import 'dart:math' gives sqrt, pow, min, max, pi.
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());
}void main() {
int bill = 347;
int given = 500;
int change = given - bill;
print('Bill : Rs $bill');
print('Given : Rs $given');
print('Change : Rs $change');
}void main() {
int n = 27;
print('$n remainder 2 = ${n % 2}');
print('Is even? ${n % 2 == 0}');
print('Is even? ${48 % 2 == 0}');
}void main() {
int marks = 56;
print('Passed? ${marks >= 33}');
print(marks >= 33 ? 'Result: PASS' : 'Result: FAIL');
print(marks >= 75 ? 'Distinction' : 'No distinction');
}void main() {
int eggs = 245;
int perTray = 30;
print('Full trays : ${eggs ~/ perTray}');
print('Left over : ${eggs % perTray}');
}void main() {
int stock = 50;
stock += 20;
print('After purchase: $stock');
stock -= 8;
print('After sale : $stock');
stock--;
print('One damaged : $stock');
}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)}');
}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}');
}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');
}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');
}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()}');
}+ - * / ~/ %. Divide / always gives a decimal.
== != > < >= <= give true or false.
&& and, || or, ! not.
+= -= ++ -- update variables.
condition ? yes : no decides in one line.
sqrt, pow, min, max, pi and rounding.
Trim spaces, make email lower case, check the length of a password.
Search, replace and split text in chats and SMS.
Pad and align text so tables look neat in a printout.
Use single ' ' or double " " quotes. Three quotes ''' ''' make a multi-line string. Prefix r gives a raw string where \ is just a character.
"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 counts characters. .toUpperCase() and .toLowerCase() change case. .trim() removes spaces at both ends.
.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);
}contains, startsWith, endsWith, indexOf search. replaceAll replaces text.
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 cuts text into a list at a separator. join on a list joins pieces back into one text.
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);
}Characters are counted from 0. s[0] is the first. substring(start, end) cuts a piece (end is not included).
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;
}
}padLeft and padRight align text. StringBuffer builds a long text efficiently by adding pieces with write.
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());
}void main() {
String raw = ' asha kumari ';
String clean = raw.trim();
print('[$raw]');
print('[$clean]');
print(clean.toUpperCase());
print('Length: ${clean.length}');
}void main() {
String first = 'Rohit';
String last = 'Kumar';
String initials = first[0] + last[0];
print(initials);
print('Welcome, $first ${last.toUpperCase()}');
}void main() {
String title = 'Learn Flutter in Ranchi';
String search = 'flutter';
print(title.contains(search));
print(title.toLowerCase().contains(search));
}void main() {
String template = 'Dear NAME, your fee of AMOUNT is due.';
String msg = template.replaceAll('NAME', 'Asha').replaceAll('AMOUNT', 'Rs 1500');
print(msg);
}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));
}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'}');
}
}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');
}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}');
}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)}');
}
}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());
}Text in quotes. Triple quotes for many lines.
length, trim, toUpperCase, toLowerCase, isEmpty.
contains, startsWith, endsWith, indexOf, replaceAll.
split makes a list, join makes text.
Start at 0. substring(start, end) excludes end.
padLeft, padRight and StringBuffer make neat output.