Sub topic 3
Generics
This chapter assumes you know classes, functions, and the basic List and Map types. It covers generics, records, pattern matching, error handling, async code, streams, and libraries.
Generics
A generic type parameter lets one function or class work with many types while the compiler still checks them.
T firstOr<T>(List<T> items, T fallback) =>
items.isEmpty ? fallback : items.first;
class Box<T extends num> {
final T value;
Box(this.value);
double doubled() => value * 2.0;
}T extends num limits T to numbers.
Records and pattern matching
A record groups several values without a class. Pattern matching checks a value's shape and pulls out its parts.
sealed class Shape {}
class Circle extends Shape {
final double r;
Circle(this.r);
}
class Square extends Shape {
final double side;
Square(this.side);
}
double area(Shape s) => switch (s) {
Circle(:var r) => 3.14159 * r * r,
Square(:var side) => side * side,
};
void main() {
final (x, y) = (1, 2);
print('$x $y ${area(Square(3))}');
}A sealed class lets the compiler confirm that a switch expression covers every subtype.
Handling errors with exceptions
Use try to run risky code, on to catch a named error type, and finally to run cleanup code in every case.
void main() {
try {
throw StateError('network down');
} on StateError catch (e) {
print('Failed: ${e.message}');
} finally {
print('done');
}
}Asynchronous code with Future, async, and await
A Future is a value that arrives later. await pauses an async function until that value is ready.
Future<String> fetchName() async {
await Future.delayed(const Duration(milliseconds: 100));
return 'Ada';
}An error thrown inside an async function surfaces at the await call, so a try block around that call catches it.
Streams and async generators
A Stream delivers many values over time. An async* function yields them, and await for reads them.
Stream<int> countTo(int n) async* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Future<void> main() async {
await for (final value in countTo(3)) {
print(value);
}
}Libraries, imports, and packages
A library is a Dart file. Import it with import, and use as to avoid name clashes. Packages are listed in pubspec.yaml and imported with package: paths.
import 'dart:math';
import 'package:http/http.dart' as http;The http import needs http listed under dependencies in pubspec.yaml, followed by dart pub get.
Exercise
Why does the area switch expression need no default case?
Show answer
Because Shape is sealed, the compiler knows every subclass, so it can confirm that all cases are covered.