Nullable types, ?, ??, ?., !, late and required · 5 h
Blueprints and real things: fields, methods, constructors, getters, static · 7 h
Reuse code with extends, override, abstract, implements and with · 7 h
Named choices, returning many values, and modern switch and destructuring · 6 h
25 class hours · 40 practice examples · Trainer: Nandan Kumar, Ranchi
A user may skip "middle name". The field is nullable.
Searching a map or list can find nothing. The result is null.
Fewer crashes means fewer bad reviews.
String can never be null. String? (with a question mark) may hold text or null. Dart refuses to let you use a nullable value as if it were sure.
String? = "maybe a String".void main() {
String name = 'Asha';
String? middle;
print(name);
print(middle);
middle = 'Kumari';
print(middle);
int? age;
print(age == null);
}value?.length calls the method only if value is not null; otherwise the answer is null and nothing crashes.
void main() {
String? a = 'Ranchi';
String? b;
print(a?.length);
print(b?.length);
print(a?.toUpperCase());
print(b?.toUpperCase());
}x ?? fallback gives the fallback when x is null. x ??= value stores the value only when x is null.
void main() {
String? nick;
print(nick ?? 'No nickname');
nick ??= 'Chotu';
print(nick);
nick ??= 'Other';
print(nick);
int? score;
print((score ?? 0) + 10);
}value! says "I promise this is not null". If you are wrong the program crashes. Use it only when you are really sure; prefer ?? or if-checks.
void main() {
String? city = 'Patna';
print(city!.length);
String? none;
try {
print(none!.length);
} catch (e) {
print('Crash avoided: value was null');
}
}After if (x != null), Dart knows x is not null inside the block (it is "promoted"). No ! needed.
return for null keeps the rest of the function clean.void show(String? text) {
if (text == null) {
print('Nothing to show');
return;
}
print('Length: ${text.length}');
}
void main() {
show('Dart');
show(null);
String? x = 'abc';
if (x != null && x.isNotEmpty) {
print(x.toUpperCase());
}
}late promises a non-null variable will be set before it is used (and can delay a heavy calculation). required forces callers to give a named parameter.
required is everywhere in Flutter widgets.class Course {
final String title;
final int fee;
Course({required this.title, required this.fee});
}
late String greeting;
void main() {
greeting = 'Namaste';
print(greeting);
late int total = 5 * 20;
print(total);
var c = Course(title: 'Dart', fee: 3000);
print('${c.title} Rs ${c.fee}');
}void main() {
String name = 'Asha';
String? phone;
print('Name : $name');
print('Phone: $phone');
phone = '98001 11111';
print('Phone: $phone');
}void main() {
String? bio;
print(bio ?? 'No bio added yet');
String? city = 'Ranchi';
print(city ?? 'City unknown');
}void main() {
String? a = 'Hello';
String? b;
print(a?.length);
print(b?.length);
print(b?.length ?? 0);
}void main() {
String? token;
if (token == null) {
print('Please log in');
} else {
print('Token is $token');
}
token = 'abc123';
print(token == null ? 'No token' : 'Token ready');
}void main() {
String? theme;
theme ??= 'light';
print(theme);
theme ??= 'dark';
print(theme);
}void main() {
var emails = {'asha': 'asha@mail.com', 'rohit': 'rohit@mail.com'};
for (var u in ['asha', 'zoya', 'rohit']) {
String? e = emails[u];
print('$u -> ${e ?? 'not registered'}');
}
print(emails['zoya']?.toUpperCase());
}String? validateName(String? v) {
if (v == null || v.trim().isEmpty) return 'Name is required';
if (v.length < 3) return 'Name is too short';
return null;
}
void main() {
for (String? t in [null, ' ', 'Al', 'Asha']) {
print('"${t ?? 'null'}" -> ${validateName(t) ?? 'OK'}');
}
}String describe({required String name, String? city, int age = 18}) {
String where = city ?? 'unknown city';
return '$name, $age, from $where';
}
void main() {
print(describe(name: 'Asha'));
print(describe(name: 'Rohit', city: 'Patna'));
print(describe(name: 'Meena', age: 21, city: 'Gaya'));
}void main() {
Map<String, dynamic> response = {
'user': {'name': 'Asha', 'address': {'city': 'Ranchi'}},
};
Map<String, dynamic> response2 = {'user': {'name': 'Rohit'}};
for (var r in [response, response2, <String, dynamic>{}]) {
var city = r['user']?['address']?['city'] ?? 'City not available';
var name = r['user']?['name'] ?? 'Guest';
print('$name lives in $city');
}
}void main() {
Map<String, int?> marks = {'Maths': 78, 'Science': null, 'English': 66};
int total = 0;
int taken = 0;
marks.forEach((sub, m) {
if (m == null) {
print('${sub.padRight(8)} absent');
return;
}
print('${sub.padRight(8)} $m');
total += m;
taken++;
});
print('Exams taken: $taken');
print('Total: $total, Average: ${taken == 0 ? 0 : (total / taken).toStringAsFixed(1)}');
}Means no value. Using it blindly crashes apps.
String can never be null; String? may be.
Safe call and fallback value.
A promise. Wrong promise means a crash.
if (x != null) lets Dart promote the type.
Set before use / must be provided.
Each student is an object made from the Student class.
BankAccount has a balance and methods deposit() and withdraw().
Every widget is an object. You will write many classes.
A class lists the fields (what it knows) and methods (what it can do). Student() builds an object. Use a dot to reach inside.
class Student {
String name = '';
int marks = 0;
void show() {
print('$name scored $marks');
}
}
void main() {
var a = Student();
a.name = 'Asha';
a.marks = 91;
var b = Student();
b.name = 'Rohit';
b.marks = 67;
a.show();
b.show();
}A constructor fills the fields when the object is made. this.name in the brackets is a shortcut that copies the argument into the field. Named constructors give extra ways to build.
Text('Hi') calls the Text constructor.class Student {
String name;
int marks;
Student(this.name, this.marks);
Student.newJoiner(this.name) : marks = 0;
void show() => print('$name: $marks');
}
void main() {
Student('Asha', 91).show();
Student.newJoiner('Kiran').show();
}Methods can read and change the fields of the object they belong to. Inside a method, fields are used by name.
class Account {
String owner;
double balance;
Account(this.owner, this.balance);
void deposit(double amount) {
balance += amount;
}
bool withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
}
void main() {
var acc = Account('Asha', 1000);
acc.deposit(500);
print(acc.withdraw(2000));
print(acc.withdraw(300));
print(acc.balance);
}A name starting with _ is private to its file. Provide a getter to read it and a setter or method to change it safely.
class Temp {
double _celsius = 0;
double get celsius => _celsius;
double get fahrenheit => _celsius * 9 / 5 + 32;
set celsius(double v) {
if (v < -273.15) {
print('Impossible temperature');
return;
}
_celsius = v;
}
}
void main() {
var t = Temp();
t.celsius = 36.5;
print(t.fahrenheit);
t.celsius = -500;
print(t.celsius);
}static belongs to the class itself, not to an object. toString() controls how an object prints. const constructors make fixed objects.
class School {
static int count = 0;
static const String name = 'BrainBit Infotech Academy';
final String student;
School(this.student) {
count++;
}
@override
String toString() => '$student @ $name';
}
void main() {
var a = School('Asha');
var b = School('Rohit');
print(a);
print(School.count);
print(b);
}Real programs keep many objects in a list, then loop, filter and sort them.
class Product {
final String name;
final double price;
Product(this.name, this.price);
}
void main() {
var items = [Product('Pen', 10), Product('Book', 150), Product('Bag', 700)];
for (var p in items) {
print('${p.name}: Rs ${p.price}');
}
var costly = items.where((p) => p.price > 100).map((p) => p.name);
print(costly.toList());
print(items.fold(0.0, (s, p) => s + p.price));
}class Student {
String name;
int marks;
Student(this.name, this.marks);
void show() {
print('$name scored $marks');
}
}
void main() {
Student('Asha', 91).show();
Student('Rohit', 67).show();
}class Rectangle {
double length, breadth;
Rectangle(this.length, this.breadth);
double area() => length * breadth;
double perimeter() => 2 * (length + breadth);
}
void main() {
var r = Rectangle(12, 8);
print('Area : ${r.area()}');
print('Perimeter : ${r.perimeter()}');
}class Book {
final String title;
final String author;
final int pages;
Book(this.title, this.author, this.pages);
@override
String toString() => '$title by $author ($pages pages)';
}
void main() {
print(Book('Godan', 'Premchand', 336));
print(Book('Wings of Fire', 'A. P. J. Abdul Kalam', 180));
}class Counter {
int value = 0;
void increment() => value++;
void reset() => value = 0;
}
void main() {
var c = Counter();
c.increment();
c.increment();
c.increment();
print(c.value);
c.reset();
print(c.value);
}class Point {
final double x, y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
Point.same(double v) : x = v, y = v;
@override
String toString() => '($x, $y)';
}
void main() {
print(Point(3, 4));
print(Point.origin());
print(Point.same(5));
}class Account {
final String owner;
double _balance = 0;
Account(this.owner, [double opening = 0]) {
_balance = opening;
}
double get balance => _balance;
bool deposit(double amt) {
if (amt <= 0) return false;
_balance += amt;
return true;
}
bool withdraw(double amt) {
if (amt <= 0 || amt > _balance) return false;
_balance -= amt;
return true;
}
}
void main() {
var a = Account('Asha', 2000);
print(a.deposit(500));
print(a.withdraw(5000));
print(a.withdraw(700));
print('Balance: Rs ${a.balance}');
}class Product {
final String name;
final double price;
final int stock;
Product(this.name, this.price, this.stock);
double get value => price * stock;
}
void main() {
var items = [Product('Pen', 10, 200), Product('Book', 150, 40), Product('Bag', 700, 5)];
items.sort((a, b) => b.value.compareTo(a.value));
for (var p in items) {
print('${p.name.padRight(5)} ${p.stock.toString().padLeft(4)} x ${p.price} = ${p.value}');
}
print('Stock value: ${items.fold(0.0, (s, p) => s + p.value)}');
}class Sensor {
double _c = 25;
double get celsius => _c;
double get fahrenheit => _c * 9 / 5 + 32;
set celsius(double v) {
if (v < -50 || v > 150) {
print('Rejected $v');
return;
}
_c = v;
}
}
void main() {
var s = Sensor();
s.celsius = 40;
print('${s.celsius} C = ${s.fahrenheit} F');
s.celsius = 900;
print(s.celsius);
}class Book {
final String title;
bool lent = false;
Book(this.title);
}
class Library {
final List<Book> books = [];
void add(String t) => books.add(Book(t));
String lend(String t) {
for (var b in books) {
if (b.title != t) continue;
if (b.lent) return '$t is already lent';
b.lent = true;
return 'Lent: $t';
}
return '$t not found';
}
}
void main() {
var lib = Library();
lib.add('Godan');
print(lib.lend('Godan'));
print(lib.lend('Godan'));
print(lib.lend('Ramayan'));
}class Item {
final String name;
final double price;
final int qty;
Item(this.name, this.price, this.qty);
double get total => price * qty;
}
class Cart {
final List<Item> items = [];
void add(Item i) => items.add(i);
double get subtotal => items.fold(0.0, (s, i) => s + i.total);
double get tax => subtotal * 0.18;
}
void main() {
var c = Cart();
c.add(Item('Notebook', 60, 5));
c.add(Item('Pen', 10, 10));
c.add(Item('Bag', 799, 1));
for (var i in c.items) {
print('${i.name.padRight(8)} ${i.qty} x ${i.price} = ${i.total}');
}
print('Subtotal : ${c.subtotal}');
print('GST 18% : ${c.tax.toStringAsFixed(2)}');
print('Payable : ${(c.subtotal + c.tax).toStringAsFixed(2)}');
}Blueprint with fields and methods.
A real instance made with ClassName(...).
Fills fields; this.x shortcut; named constructors.
_name hides data; getters and setters control access.
Belongs to the class, shared by all objects.
Loop, filter, sort and total real data.
UPI, Card and NetBanking are all Payment types with a pay() method.
Every widget extends StatelessWidget or StatefulWidget.
Teacher and Student extend Person.
class Teacher extends Person gets everything Person has. super reaches the parent class, for example to pass values to its constructor.
class Person {
String name;
Person(this.name);
void intro() => print('I am $name');
}
class Teacher extends Person {
String subject;
Teacher(String name, this.subject) : super(name);
void teach() => print('$name teaches $subject');
}
void main() {
var t = Teacher('Mr Sinha', 'Maths');
t.intro();
t.teach();
}A child class can change a method with @override. A list of parent type can hold different children; each answers in its own way. That is polymorphism.
for (p in payments) p.pay(): one call, many behaviours.class Animal {
void sound() => print('Some sound');
}
class Dog extends Animal {
@override
void sound() => print('Woof');
}
class Cat extends Animal {
@override
void sound() {
print('Meow');
}
}
void main() {
List<Animal> zoo = [Dog(), Cat(), Animal()];
for (var a in zoo) {
a.sound();
}
}An abstract class cannot be built itself. It lists methods that children must write. It is a contract: "every shape must be able to give an area".
abstract class Shape {
double area();
void describe() => print('Area is ${area()}');
}
class Square extends Shape {
double side;
Square(this.side);
@override
double area() => side * side;
}
class Circle extends Shape {
double r;
Circle(this.r);
@override double area() => 3.14 * r * r;
}
void main() {
Square(4).describe();
Circle(2).describe();
}Every class is also an interface. implements says "I promise to provide all these members" without inheriting any code. A class can implement many interfaces.
abstract class Printable {
void printMe();
}
abstract class Savable {
void save();
}
class Report implements Printable, Savable {
@override
void printMe() => print('Printing report');
@override
void save() => print('Saving report');
}
void main() {
var r = Report();
r.printMe();
r.save();
print(r is Printable);
}A mixin is a bundle of features that you can add to any class with with. It is how unrelated classes share a feature, like logging.
mixin Logger {
void log(String m) => print('[LOG] $m');
}
mixin Walker {
void walk() => print('Walking');
}
class Robot with Logger, Walker {
String name;
Robot(this.name);
}
void main() {
var r = Robot('R2');
r.log('Started ${r.name}');
r.walk();
}is tests a type. as converts. After an is check Dart treats the object as that type.
class Animal {}
class Dog extends Animal {
void bark() => print('Woof!');
}
void main() {
Animal a = Dog();
print(a is Dog);
print(a is Animal);
if (a is Dog) {
a.bark();
}
Dog d = a as Dog;
d.bark();
}class Person {
String name;
Person(this.name);
void intro() => print('Hello, I am $name');
}
class Student extends Person {
int roll;
Student(String name, this.roll) : super(name);
}
void main() {
var s = Student('Asha', 12);
s.intro();
print('Roll ${s.roll}');
}class Vehicle {
void start() => print('Vehicle starting');
}
class Bike extends Vehicle {
@override
void start() => print('Kick start the bike');
}
class Car extends Vehicle {
@override
void start() => print('Press the start button');
}
void main() {
Vehicle().start();
Bike().start();
Car().start();
}class Notification {
void send() => print('Sending notification');
}
class SmsNotification extends Notification {
@override
void send() {
super.send();
print('...via SMS');
}
}
void main() {
SmsNotification().send();
}abstract class Shape {
String name;
Shape(this.name);
double area();
void show() => print('$name area = ${area()}');
}
class Rect extends Shape {
double w, h;
Rect(this.w, this.h) : super('Rectangle');
@override
double area() => w * h;
}
class Tri extends Shape {
double b, h;
Tri(this.b, this.h) : super('Triangle');
@override
double area() => 0.5 * b * h;
}
void main() {
Rect(4, 5).show();
Tri(6, 3).show();
}mixin Logger {
void log(String m) => print('[LOG] $m');
}
class Shop with Logger {
void sell() => log('Item sold');
}
class School with Logger {
void admit() => log('Student admitted');
}
void main() {
Shop().sell();
School().admit();
}abstract class Payment {
double amount;
Payment(this.amount);
void pay();
}
class CardPayment extends Payment {
CardPayment(double a) : super(a);
@override
void pay() => print('Card charged Rs $amount (+2% fee = ${amount * 1.02})');
}
class UpiPayment extends Payment {
UpiPayment(double a) : super(a);
@override
void pay() => print('UPI payment of Rs $amount done');
}
class CashPayment extends Payment {
CashPayment(double a) : super(a);
@override
void pay() => print('Collected Rs $amount in cash');
}
void main() {
List<Payment> bills = [CardPayment(1000), UpiPayment(450), CashPayment(200)];
for (var b in bills) {
b.pay();
}
}abstract class Staff {
String name;
Staff(this.name);
double salary();
}
class Teacher extends Staff {
int periods;
Teacher(String n, this.periods) : super(n);
@override
double salary() => 20000 + periods * 300;
}
class Clerk extends Staff {
Clerk(String n) : super(n);
@override double salary() => 18000;
}
class Principal extends Staff {
Principal(String n) : super(n);
@override double salary() => 55000;
}
void main() {
var staff = <Staff>[Teacher('Mr Sinha', 24), Clerk('Mrs Devi'), Principal('Dr Rao')];
double total = 0;
for (var s in staff) {
print('${s.name.padRight(9)} Rs ${s.salary()}');
total += s.salary();
}
print('Payroll Rs $total');
}abstract class Notifier {
void notify(String msg);
}
class Sms implements Notifier {
@override
void notify(String msg) => print('SMS: $msg');
}
class Email implements Notifier {
@override
void notify(String msg) => print('Email: $msg');
}
class Push implements Notifier {
@override
void notify(String msg) => print('Push: $msg');
}
void alertAll(List<Notifier> channels, String m) {
for (var c in channels) {
c.notify(m);
}
}
void main() {
alertAll([Sms(), Email(), Push()], 'Fees due on 5th');
}mixin CanFly {
void fly() => print('$runtimeType is flying');
}
mixin CanSwim {
void swim() => print('$runtimeType is swimming');
}
mixin CanRun {
void run() => print('$runtimeType is running');
}
class Duck with CanFly, CanSwim, CanRun {}
class Fish with CanSwim {}
class Eagle with CanFly, CanRun {}
void main() {
var d = Duck();
d.fly();
d.swim();
d.run();
Fish().swim();
Eagle().fly();
print(d is CanSwim);
print(Fish() is CanFly);
}mixin Priced {
double basePrice = 0;
double get priceWithGst => basePrice * 1.12;
}
abstract class Item {
String title;
Item(this.title);
String describe();
}
class Book extends Item with Priced {
int pages;
Book(String t, this.pages, double p) : super(t) { basePrice = p; }
@override
String describe() => 'Book "$title", $pages pages, Rs ${priceWithGst.toStringAsFixed(2)}';
}
class Dvd extends Item with Priced {
int minutes;
Dvd(String t, this.minutes, double p) : super(t) { basePrice = p; }
@override
String describe() => 'DVD "$title", $minutes min, Rs ${priceWithGst.toStringAsFixed(2)}';
}
void main() {
List<Item> shelf = [Book('Godan', 336, 250), Dvd('Lagaan', 224, 150)];
for (var i in shelf) {
print(i.describe());
}
}Child reuses parent code; super reaches the parent.
Child replaces a parent method. Polymorphism.
A contract class that cannot be built directly.
Promise to provide all members, no code reused.
Add shared abilities to any class.
Test and convert types.
Status is an enum: placed, packed, shipped, delivered.
A record returns (min, max) together.
loading, success and error are modelled as enum or sealed classes.
An enum lists all allowed values. Typing mistakes become impossible: Status.shiped is an error, while the string 'shiped' would silently be wrong.
enum Status { placed, shipped, delivered }
void main() {
Status s = Status.shipped;
print(s);
print(s.name);
print(s.index);
print(Status.values);
for (var x in Status.values) {
print('${x.index}: ${x.name}');
}
}Enums can carry data and methods. Each value is made with the constructor.
enum Plan {
free(0, 'Basic'),
pro(499, 'Advanced'),
team(1499, 'All features');
final int price;
final String label;
const Plan(this.price, this.label);
String get info => '$name: Rs $price ($label)';
}
void main() {
for (var p in Plan.values) {
print(p.info);
}
}A record groups values in round brackets without making a class: (int, int). Great when a function must return two things. Fields: $1, $2, or names.
(int, int) minMax(List<int> a) {
var s = [...a]..sort();
return (s.first, s.last);
}
void main() {
var r = minMax([40, 7, 93, 18]);
print(r);
print(r.$1);
print(r.$2);
var person = (name: 'Asha', age: 16);
print(person.name);
print(person);
}Unpack values into variables in one line. Works with records, lists and maps.
(a, b) = (b, a) swaps two variables with no helper.void main() {
var (a, b) = (10, 20);
print('$a $b');
(a, b) = (b, a);
print('$a $b');
var [first, second, ...rest] = [1, 2, 3, 4, 5];
print('$first $second $rest');
var {'name': n, 'age': g} = {'name': 'Rohit', 'age': 17};
print('$n $g');
}A switch expression returns a value: var x = switch (v) { pattern => result, ... };. Patterns can compare values, ranges and types, and add a when guard.
String grade(int m) => switch (m) {
>= 90 => 'A+',
>= 75 => 'A',
>= 60 => 'B',
>= 33 => 'C',
_ => 'Fail',
};
String day(int d) => switch (d) {
6 || 7 => 'Weekend',
_ => 'Weekday',
};
void main() {
print(grade(95));
print(grade(40));
print(day(7));
print(day(2));
Object o = 42;
var t = switch (o) { int n when n > 10 => 'big int', int() => 'int', String() => 'text', _ => 'other' };
print(t);
}A sealed class has a fixed family of children. A switch over it must handle every child, or Dart refuses to compile. Perfect for results like loading, success and error.
sealed class Result {}
class Success extends Result {
final String data;
Success(this.data);
}
class Failure extends Result {
final String error;
Failure(this.error);
}
String show(Result r) => switch (r) {
Success(data: var d) => 'Got $d',
Failure(error: var e) => 'Problem: $e',
};
void main() {
print(show(Success('Course list')));
print(show(Failure('No internet')));
}enum Day { mon, tue, wed, thu, fri, sat, sun }
void main() {
Day today = Day.sat;
print(today.name);
print(today == Day.sat);
print('Position: ${today.index}');
print(Day.values.length);
}enum Status { placed, shipped, delivered }
String message(Status s) {
switch (s) {
case Status.placed: return 'We got your order';
case Status.shipped: return 'On the way to Ranchi';
case Status.delivered: return 'Delivered. Enjoy!';
}
}
void main() {
for (var s in Status.values) {
print('${s.name}: ${message(s)}');
}
}void main() {
int a = 5, b = 9;
print('Before: $a $b');
(a, b) = (b, a);
print('After : $a $b');
}(int, int) divide(int a, int b) => (a ~/ b, a % b);
void main() {
var r = divide(17, 5);
print('Quotient ${r.$1}');
print('Remainder ${r.$2}');
var (q, rem) = divide(100, 7);
print('$q and $rem');
}String grade(int m) => switch (m) {
>= 90 => 'A+',
>= 75 => 'A',
>= 60 => 'B',
>= 33 => 'C',
_ => 'Fail',
};
void main() {
for (var m in [95, 80, 61, 40, 12]) {
print('$m -> ${grade(m)}');
}
}enum Plan {
free(0, 1),
pro(499, 10),
team(1499, 50);
final int price;
final int users;
const Plan(this.price, this.users);
double get perUser => users == 0 ? 0 : price / users;
}
void main() {
for (var p in Plan.values) {
print('${p.name.padRight(5)} Rs ${p.price.toString().padLeft(5)} users ${p.users} per user ${p.perUser.toStringAsFixed(1)}');
}
}({int min, int max, double avg}) stats(List<int> v) {
var s = [...v]..sort();
double avg = v.fold(0, (a, b) => a + b) / v.length;
return (min: s.first, max: s.last, avg: avg);
}
void main() {
var r = stats([72, 85, 91, 64, 78]);
print('Lowest ${r.min}');
print('Highest ${r.max}');
print('Average ${r.avg}');
print(r);
}void main() {
var row = ['Asha', 'Ranchi', 16];
var [name, city, age] = row;
print('$name from $city, age $age');
var info = {'course': 'Dart', 'fee': 3000};
var {'course': c, 'fee': f} = info;
print('$c costs Rs $f');
for (var (x, y) in [(1, 2), (3, 4)]) {
print('x=$x y=$y');
}
}sealed class Result {}
class Loading extends Result {}
class Data extends Result {
final List<String> items;
Data(this.items);
}
class Failed extends Result {
final String why;
Failed(this.why);
}
String screen(Result r) => switch (r) {
Loading() => 'Show spinner',
Data(items: var i) when i.isEmpty => 'Show "no courses yet"',
Data(items: var i) => 'Show ${i.length} courses: ${i.join(', ')}',
Failed(why: var w) => 'Show error: $w',
};
void main() {
for (Result r in [Loading(), Data([]), Data(['Dart', 'Flutter']), Failed('Timeout')]) {
print(screen(r));
}
}sealed class Shape {}
class Circle extends Shape {
final double r;
Circle(this.r);
}
class Rect extends Shape {
final double w, h;
Rect(this.w, this.h);
}
class Tri extends Shape {
final double b, h;
Tri(this.b, this.h);
}
double area(Shape s) => switch (s) {
Circle(r: var r) => 3.14159 * r * r,
Rect(w: var w, h: var h) => w * h,
Tri(b: var b, h: var h) => 0.5 * b * h,
};
void main() {
var shapes = <Shape>[Circle(3), Rect(4, 5), Tri(6, 7)];
for (var s in shapes) {
print('${s.runtimeType}: ${area(s).toStringAsFixed(2)}');
}
}Fixed named choices. name, index and values.
Values can carry fields and methods.
(a, b) bundles values; $1, $2 or named fields.
Unpack records, lists and maps in one line.
Returns a value; patterns, guards and _.
Closed family; switch must cover every case.