Meet Flutter, Dart and your very first app · 3 h
Variables, numbers, text, decisions and loops · 4 h
Reuse code with functions, store many values in List, Map and Set · 4 h
Classes, inheritance, enums, Future, async/await and exceptions · 4 h
A kirana store in Ranchi can have its own Android app: product list, offers and a call button.
Timetable, notice board and fee receipts for students, like the apps coaching institutes use.
Build the first version of an idea in weeks, on Android and iPhone together.
Flutter is a free toolkit to build apps. You write code once and it runs on Android, iPhone, web and Windows.
Without Flutter you need one team for Android and another for iPhone. With Flutter, one team is enough.
Flutter draws every pixel itself, so apps run at 60 frames per second and look the same on every phone.
Flutter costs nothing. Lakhs of developers use it, so you will always find help and packages.
Flutter is the toolkit. Dart is the language you write in. If you learned Java, C or JavaScript, Dart will feel familiar.
Dart reads almost like English: print('Namaste');
Dart is compiled to real machine code, so the app opens quickly.
Dart checks types, so many mistakes are caught before the app runs.
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.
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)),
),
),
));
}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.
A widget that holds others, such as Column.
A widget placed inside, such as Text.
All widgets together, from MaterialApp at the top to the smallest Text.
Download from flutter.dev, unzip to C:\src\flutter and add its bin folder to PATH.
Android Studio (with the Flutter plugin) or VS Code with the Flutter extension. Both are free.
Open a terminal and type flutter doctor. It lists what is missing, with green ticks when ready.
In Android Studio open Device Manager and create an emulator, or plug in your own Android phone with USB debugging on.
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.
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, imagesmain → 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')),
),
);
}
}Save the file (Ctrl+S) and the screen updates in about one second. Your data stays. Shortcut: r in the terminal.
Starts the app again from the beginning. Use it after changing main() or app state. Shortcut: R.
Stop and run again. Needed after adding a package or an image to pubspec.yaml.
Each hard idea has a step-by-step animation. Press Next or Auto play.
Every example has a live phone or console. Tap buttons on the phone: it really works.
Each example ends with a small task. Open it in the Lab, change the code, press Run.
Arrow keys move slides, M menu, L Code Lab, F full screen. Buttons are at the bottom right.
void main() {
runApp(const MaterialApp(
home: Scaffold(
body: Center(
child: Text(
'Hello Ranchi!',
style: TextStyle(fontSize: 34),
),
),
),
));
}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,
),
),
),
),
),
));
}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'),
),
),
));
}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)),
),
),
),
));
}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'),
],
),
),
),
));
}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')]),
],
),
),
),
));
}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'),
],
),
],
),
),
),
));
}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),
),
);
}
}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))]),
],
),
),
),
),
));
}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)),
),
],
),
),
),
));
}One code for Android, iPhone, web and desktop.
The language of Flutter, easy to read.
Small building blocks; the whole app is a tree of them.
You mostly work in lib/main.dart and pubspec.yaml.
main() calls runApp(), which shows MaterialApp and Scaffold.
Save and see the change in one second.
Every shop app adds price x quantity, then GST, then discount. That is variables and operators.
Schools turn marks into grades using if / else. Same code, different data.
Showing 100 products, sending 500 reminders, building a table: all done with loops.
Every Dart program starts at main(). print() shows a line of text in the output. Each instruction ends with a semicolon ;.
void main() {
print('Namaste Ranchi!');
print(2 + 3);
print('Total = ${10 * 5}');
}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.
Whole numbers: int age = 17;
Numbers with a decimal point: double price = 49.5;
Text in quotes: String city = 'Ranchi';
Only true or false: bool isPaid = true;
var lets Dart guess the type. final is set once and never changed. const is fixed even before the app runs.Put $name inside quotes to insert a variable. Use ${...} for a calculation. This is easier than joining with +.
\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());
}+ - * / and % (remainder). 10 / 4 is 2.5, but 10 ~/ 4 is 2 (whole part only).
== != > < >= <= give true or false: age >= 18.
&& (and), || (or), ! (not): age >= 18 && hasId.
count++, total += 50, x *= 2 save typing.
= stores a value, two == compares two values.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.
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');
}A loop repeats a block of code. break stops the loop early, continue skips to the next round.
// 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 means "no value". A student may not have an email yet.
String? email; means the box may hold text or null.
email ?? 'not given' uses the default when email is null.
email?.length returns null instead of crashing.
It tells the line number and the problem. Read the first line first.
Missing ;, wrong spelling (Print vs print), unclosed brackets.
Use camelCase for variables: totalMarks. Use clear names, not x1.
// note explains code to humans. Dart ignores it.
void main() {
print('Namaste, Ranchi!');
print('Welcome to the Flutter course');
print('BrainBit Infotech');
}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)}');
}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)}');
}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('--------------------');
}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).');
}
}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');
}void main() {
int n = 7;
print('Table of $n');
for (int i = 1; i <= 10; i++) {
print('$n x $i = ${n * i}');
}
}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');
}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)}');
}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');
}int, double, String, bool store data. final and const never change.
$name and ${a + b} put values inside text.
+ - * / % ~/ and comparison, logical operators.
if / else if / else, switch for many exact choices.
for, while and for-in repeat work; break and continue control them.
String? may be null; ?? gives a default value.
Cart items, chat messages, news headlines: all are lists.
A student is a map: name, roll, city. A JSON reply from the internet is also a map.
Write the GST rule once as a function and use it on every screen.
A function is a named block of code. You give it input (parameters), it does work and can give back a result (return value).
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));
}Named parameters in { } make calls easy to read. required means you must give it. A default value (= 18) is used when you skip it.
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'));
}A List holds many values in order. Counting starts from 0.
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'));
}A Map stores pairs: a key (label) and its value. You find a value by its key, not by position.
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'));
}A Set keeps each value only once: {1, 2, 2, 3} becomes {1, 2, 3}.
Set<String> tags = {'a', 'b'}; or list.toSet().
add, contains, union, intersection, difference.
Unique tags, selected checkboxes, distinct cities of all orders.
These methods take a small function (lambda) and apply it to every item. They replace long loops with one line.
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'));
}Dart lets you put if, for and ... (spread) right inside a list. Flutter uses this a lot to show a widget only when needed.
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);
}String? email; may be null.
email ?? 'not given'
email?.length gives null, not a crash.
email ??= 'guest@x.in';
void greet(String name) {
print('Namaste $name, welcome to BrainBit Infotech!');
}
void main() {
greet('Asha');
greet('Rohit');
greet('Pooja');
}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');
}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));
}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]}');
}
}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')}');
}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)}');
}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)}');
}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)}');
}
}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');
}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)}');
}Name a block of code, give it parameters, return a result.
Positional, [optional], {named} and required, with defaults.
Ordered items, index from 0: add, insert, remove, length.
Map = key and value (like JSON). Set = unique values.
Transform, filter and combine items without long loops.
? ?? ?. ??= handle missing values safely.
A Student, a Product, an Order: each is a class. Each real student becomes an object made from it.
While the app waits for a server reply, the screen keeps working. That is async / await.
If the internet fails, show a friendly message instead of closing the app.
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.
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();
}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.
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();
}A function inside a class: void deposit(int x).
Looks like a field, works like a function: double get area => w * h;
A name starting with _ is private to its file. Others cannot change it by mistake.
Decides how print(object) looks. Override it to print nicely.
deposit() and withdraw() where rules are checked.An enum lists every allowed choice. Using it prevents spelling mistakes like 'shiped'.
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');
}
}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.
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();
}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.
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));
}
}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.
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');
}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.
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');
}
}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();
}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();
}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}');
}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)}');
}
}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');
}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)}');
}
}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');
}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('---');
}
}
}_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);
}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}');
}A blueprint and the real things built from it.
this.x shorthand, named parameters, named constructors.
get area => ...; and _name for hidden fields.
A fixed list of choices, safe from typing mistakes.
extends, super, @override, abstract and polymorphism.
Future, async / await, and try / catch / finally.