TExcelTAD
Home › Flutter › Dart Inheritance & Mixins

Dart Inheritance & Mixins

Classes can build on each other. Dart supports inheritance (extends), interfaces (implements), abstract classes, mixins (with) and, since Dart 3, sealed classes and other class modifiers. Flutter's whole widget library is a big inheritance tree: Text extends StatelessWidget, which extends Widget.

extends: inheriting from a superclass

A subclass inherits every field and method of its superclass and can override methods to change their behaviour. Use super to call the parent's version.

dart · try it yourself
class Animal {
  final String name;
  Animal(this.name);

  String sound() => '...';
  void speak() => print('$name: ${sound()}');
}

class Cat extends Animal {
  Cat(super.name);

  @override
  String sound() => 'Meow';
}

class Kitten extends Cat {
  Kitten(super.name);

  @override
  String sound() => '${super.sound()} (tiny)';
}

void main() {
  final animals = [Animal('Generic'), Cat('Tom'), Kitten('Kiki')];
  for (final a in animals) {
    a.speak();
  }
  print(animals[2] is Animal);
}
Generic: ...
Tom: Meow
Kiki: Meow (tiny)
true

Dart has single inheritance: a class extends exactly one superclass (if you don't write extends, it extends Object). Notice Cat(super.name) — a super parameter that forwards name to Animal's constructor.

Abstract classes

An abstract class can't be instantiated. It may declare methods without a body that subclasses must implement. This is how Flutter defines StatelessWidget — it leaves build for you to write.

dart · try it yourself
abstract class Shape {
  double get area;
  String get name;

  void describe() => print('$name with area ${area.toStringAsFixed(1)}');
}

class Square extends Shape {
  final double side;
  Square(this.side);

  @override
  double get area => side * side;
  @override
  String get name => 'Square';
}

class Circle extends Shape {
  final double r;
  Circle(this.r);

  @override
  double get area => 3.14159 * r * r;
  @override
  String get name => 'Circle';
}

void main() {
  final shapes = <Shape>[Square(3), Circle(2)];
  for (final s in shapes) {
    s.describe();
  }
}
Square with area 9.0
Circle with area 12.6

implements: interfaces

Every class in Dart also defines an implicit interface. With implements, a class promises to provide all members of another type — but it inherits no code, so you must write everything yourself. A class can implement many interfaces.

dart · try it yourself
abstract interface class Printable {
  String printLabel();
}

abstract interface class Priced {
  double get price;
}

class Book implements Printable, Priced {
  final String title;
  @override
  final double price;

  Book(this.title, this.price);

  @override
  String printLabel() => '"$title" - \$price';
}

void main() {
  final b = Book('Dart Apprentice', 29.0);
  print(b.printLabel());
  Priced p = b;
  print(p.price);
}
"Dart Apprentice" - $29.0
29.0

Mixins: reusing code across classes

A mixin is a bundle of fields and methods you can "mix into" any class with with. Mixins solve the problem of sharing behaviour between classes that don't share a parent. Flutter uses them for things like SingleTickerProviderStateMixin in animations.

dart · try it yourself
mixin Swimmer {
  void swim() => print('$runtimeType is swimming');
}

mixin Flyer {
  int altitude = 0;
  void fly(int meters) {
    altitude += meters;
    print('$runtimeType flies to $altitude m');
  }
}

class Bird {}

class Duck extends Bird with Swimmer, Flyer {}

class Fish with Swimmer {}

void main() {
  final duck = Duck();
  duck.swim();
  duck.fly(10);
  duck.fly(5);
  Fish().swim();
  print(duck is Flyer);
}
Duck is swimming
Duck flies to 10 m
Duck flies to 15 m
Fish is swimming
true

A mixin can restrict which classes may use it with mixin Name on SomeClass, which also lets the mixin call SomeClass members.

Sealed classes and exhaustive switches

A sealed class can only be extended in its own file, so the compiler knows every possible subtype. A switch over it must handle all of them — perfect for modelling states such as loading / success / error.

dart · try it yourself
sealed class LoadState {}

class Loading extends LoadState {}

class Success extends LoadState {
  final List<String> items;
  Success(this.items);
}

class Failure extends LoadState {
  final String message;
  Failure(this.message);
}

String render(LoadState state) => switch (state) {
      Loading() => 'Spinner...',
      Success(:final items) => 'Showing ${items.length} items',
      Failure(:final message) => 'Error: $message',
    };

void main() {
  print(render(Loading()));
  print(render(Success(['a', 'b', 'c'])));
  print(render(Failure('offline')));
}
Spinner...
Showing 3 items
Error: offline

If you later add a new subclass, every switch that doesn't handle it becomes a compile error — the compiler points you to every place you need to update.

Class modifiers at a glance

Modifier Effect
abstract Cannot be instantiated; may have unimplemented members
interface Others can implement it, but not extend it (outside its library)
base Others can extend it, but not implement it (outside its library)
final Cannot be extended or implemented outside its library
sealed Abstract + fixed set of subtypes, enables exhaustive switch
mixin Declares a mixin to use with with

Test yourself

How many classes can a Dart class extend?

  1. Zero
  2. Exactly one
  3. Up to two
  4. Any number

What does implements give you compared with extends?

  1. All the parent's code
  2. Only the type contract — you must implement every member
  3. Access to private members
  4. Nothing at all

Why are sealed classes useful with switch?

  1. They make switch faster
  2. The compiler can check that all subtypes are handled
  3. They allow fall-through
  4. They remove the need for patterns