Beyond Classes: Interfaces, Mixins, Generics, and Async Work
This chapter tours the rest of Dart's toolkit in brief. Prerequisites: you already know basic Dart classes and methods from earlier chapters.
Abstract Classes and Interfaces
An abstract class is a blueprint. It lists what its children must do but does not do it itself. You cannot create one directly. Any class in Dart automatically acts as an interface too — a promise of certain behaviors — using the implements keyword.
abstract class Shape {
double area();
}
class Circle implements Shape {
final double radius;
Circle(this.radius);
@override
double area() => 3.14159 * radius * radius;
}
void main() {
final Shape s = Circle(2);
print(s.area()); // 12.56636
}Mixins
A mixin shares behavior across unrelated classes. Use mixin to define one and with to add it.
mixin Logger {
void log(String msg) => print('[log] $msg');
}
class Bank with Logger {}Generics
Generics let you write one function or class that works with any type, safely. List<String> means "a list that only holds text."
T firstOf<T>(List<T> items) => items[0];Exceptions and Error Handling
An exception is a problem that stops your code mid-run. Wrap risky work in try, and respond in catch.
try {
int x = int.parse('oops');
} catch (e) {
print('failed: $e');
}Futures, async, and await
A Future is a value that arrives later, like a meal ordered at a restaurant. Mark a function async, then use await to pause until the value arrives — without freezing your program.
Future<String> fetch() async {
await Future.delayed(Duration(seconds: 1));
return 'done';
}Streams
A Stream is like a Future, but it delivers many values over time — like a radio broadcast.
await for (final i in Stream.periodic(Duration(milliseconds: 100), (i) => i).take(3)) {
print('tick $i');
}Isolates
Dart runs your code in isolates: separate workers with their own memory that talk by passing messages. This avoids the locking headaches of shared-memory threading.
Packages, pub, and Tooling
Pub is Dart's package manager — a storehouse of free code others wrote. Run dart pub add <package> to use one, and dart run to execute your program. The dart command also formats and analyzes your code for you.
Exercise
What is the difference between a Future and a Stream?
Show answer
A Future delivers exactly one value later. A Stream delivers many values over time, like a series of events you listen to.
Spotted a mistake, or code that does not work?