Implicit interfaces

suggest change

Dart has no interface declaration like Java or C#. Instead, every class implicitly defines an interface: the set of its instance members (methods, getters, setters and operators). Any other class can promise to provide that interface by naming the class after implements:

class FakePoint implements Point { ... }

implements inherits no code at all. It only makes FakePoint a subtype of Point, so a FakePoint can be passed anywhere a Point is expected, and in exchange the compiler requires FakePoint to provide every member of Point's interface itself.

This article covers:

For a shorter overview alongside extends and mixins, see Inheritance.

What the implicit interface contains

Here's an ordinary class with a bit of everything: constructors, a final field, a mutable field, a static field, a getter, a setter, a method and an operator:

class Point {
  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;

  final int x;
  int y;
  static int created = 0;

  int get sum => x + y;
  set both(int v) => y = v;

  double distanceTo(Point other) {
    final dx = x - other.x;
    final dy = y - other.y;
    return (dx * dx + dy * dy).toDouble();
  }

  Point operator +(Point other) => Point(x + other.x, y + other.y);

  @override
  String toString() => 'Point($x, $y)';
}

class FakePoint implements Point {
  @override
  int get x => 1;

  @override
  int y = 2;

  @override
  int get sum => 100;

  @override
  set both(int v) {}

  @override
  double distanceTo(Point other) => 0;

  @override
  Point operator +(Point other) => this;

  @override
  String toString() => 'FakePoint';
}

void main() {
  Point p = FakePoint();
  print(p);
  print(p + Point(3, 4));
  print(p.sum);
  print(p is Point);
  print(p is FakePoint);
}

Output:

FakePoint
FakePoint
100
true
true

The interface of Point consists of:

Members inherited from Object don't have to be written out, because FakePoint implicitly extends Object and inherits them from there. Overriding toString above was optional.

What is not part of the interface:

Leave out any required member and the analyzer lists what's missing:

class Point {
  Point(this.x, this.y);
  final int x;
  int y;
}

class Empty implements Point {}
error - Missing concrete implementations of 'getter Point.x', 'getter Point.y',
and 'setter Point.y'. Try implementing the missing methods, or make the class
abstract. - non_abstract_class_inherits_abstract_member

And constructors and statics really aren't carried over:

class FakePoint implements Point {
  @override
  int get x => 1;
}

void main() {
  print(FakePoint.created);      // error: The getter 'created' isn't defined
                                 // for the type 'FakePoint'.
  final p = FakePoint.origin();  // error: The method 'origin' isn't defined
                                 // for the type 'FakePoint'.
}

Fields become getters and setters

From the interface's point of view there is no such thing as a field. A final int x field is just a getter int get x, and a mutable int y field is a getter plus a setter set y(int value).

That means you can satisfy a field with any of these:

The reverse also holds: a field in an implementing class can satisfy a getter or a getter/setter pair. Code that uses the interface can't tell the difference, which is why changing a field into a getter is never a breaking change for callers.

implements vs extends

With extends, a subclass inherits the superclass's code, runs its constructor and can call super. With implements, none of that happens. There is no superclass implementation to call:

class Logger {
  void log(String msg) => print(msg);
}

class Prefixed implements Logger {
  @override
  void log(String msg) => super.log('> $msg');
}
error - The method 'log' is always abstract in the supertype.
- abstract_super_member_reference

super here refers to Object, which has no log. If you want to reuse Logger.log, either extends Logger or hold a Logger in a field and delegate to it (see Composition and delegation).

Also, the constructor and field initializers of the implemented class never run. An implementation starts from a blank slate, which is exactly what you want for test doubles: a fake of a class that opens network connections in its constructor opens nothing.

Implementing several interfaces

A class can have only one superclass, but it can implement any number of interfaces. Each one adds a supertype:

class Reader {
  String read(int count) => 'x' * count;
}

class Closer {
  void close() => print('closed');
  String get name => 'closer';
}

class Named {
  Object get name => 'named';
}

class FileHandle implements Reader, Closer, Named {
  FileHandle(this.name);

  @override
  final String name; // satisfies both Closer.name (String) and Named.name (Object)

  @override
  String read(int count) => 'data from $name'.substring(0, count);

  @override
  void close() => print('$name closed');
}

void consume(Reader r) => print(r.read(9));
void finish(Closer c) => c.close();

void main() {
  final f = FileHandle('log.txt');
  consume(f);
  finish(f);
  Named n = f;
  print(n.name);
}

Output:

data from
log.txt closed
log.txt

When two interfaces declare a member with the same name, a single implementation must be a valid override of both. String get name works for Closer.name (String) and Named.name (Object) because String is a subtype of Object. If the types are incompatible, no implementation can satisfy both:

class A {
  String get id => 'a';
}

class B {
  int get id => 1;
}

class C implements A, B {
  @override
  String get id => 'c';
}
error - 'C.id' ('String Function()') isn't a valid override of 'B.id'
('int Function()'). - invalid_override

In that case the two interfaces simply can't be combined in one class. Use two separate adapter objects instead.

Rules for implementing members

An implementation doesn't have to copy the signature exactly. It must be a valid override, which means it has to accept every call the interface allows and return something the caller can use:

class Formatter {
  String format(int value, {int width = 8}) => '$value'.padLeft(width);
}

class HexFormatter implements Formatter {
  // Wider parameter type (num instead of int), extra optional parameter,
  // and its own default for `width`.
  @override
  String format(num value, {int width = 4, bool upper = false}) {
    final hex = value.toInt().toRadixString(16).padLeft(width, '0');
    return upper ? hex.toUpperCase() : hex;
  }
}

void main() {
  Formatter f = Formatter();
  print('[${f.format(255)}]');
  f = HexFormatter();
  print('[${f.format(255)}]');
  print('[${HexFormatter().format(255, upper: true, width: 6)}]');
}

Output:

[     255]
[00ff]
[0000FF]

Notice the second line: the static type of f is Formatter, whose default width is 8, yet the call padded to 4. Default values belong to the implementation, not to the interface. They aren't inherited, so every implementation must declare its own, and callers who rely on a particular default should pass the argument explicitly.

These implementations break the rules:

class Bad1 implements Formatter {
  @override
  String format(int value) => '$value'; // dropped {width}
}

class Bad2 implements Formatter {
  @override
  Object format(int value, {int width = 8}) => value; // wider return type
}

class Bad3 implements Formatter {
  @override
  String format(int value, {required int width}) => '$value'; // now required
}
error - 'Bad1.format' ('String Function(int)') isn't a valid override of
'Formatter.format' ('String Function(int, {int width})'). - invalid_override
error - 'Bad2.format' ('Object Function(int, {int width})') isn't a valid
override of 'Formatter.format' ('String Function(int, {int width})').
error - 'Bad3.format' ('String Function(int, {required int width})') isn't a
valid override of 'Formatter.format' ('String Function(int, {int width})').

Narrowing a parameter type (say, Point to FakePoint) is also an error unless you mark the parameter covariant, which moves the check to runtime. See Overriding.

The private member trap

Privacy in Dart is per library (see Libraries and visibility). This has an odd consequence for implicit interfaces:

That's fine until the original library calls a private member on an object it didn't create:

// file: account.dart
class Account {
  Account(this.owner, this._balance);

  final String owner;
  int _balance;

  int get balance => _balance;

  void transferTo(Account other, int amount) {
    _balance -= amount;
    other._balance += amount; // touches a private member of `other`
  }
}
// file: main.dart
import 'account.dart';

class FakeAccount implements Account {
  @override
  String get owner => 'fake';

  @override
  int get balance => 0;

  @override
  void transferTo(Account other, int amount) {}
}

void main() {
  final alice = Account('alice', 100);
  try {
    alice.transferTo(FakeAccount(), 30);
  } catch (e) {
    print(e.runtimeType);
    print(e);
  }
  print(alice.balance);
}

dart analyze reports no issues, but running it prints:

NoSuchMethodError
NoSuchMethodError: Class 'FakeAccount' has no instance getter '_balance'.
Receiver: Instance of 'FakeAccount'
Tried calling: _balance
70

Worse, the failure came halfway through the method: Alice lost 30 and nobody received it.

If your class relies on private members of other instances of the same type, mark it base. Then every subtype must inherit your implementation, and implements from another library becomes a compile error:

base class Account {
  // ... same as before
}
error - The class 'Account' can't be implemented outside of its library
because it's a base class. - invalid_use_of_type_outside_library
error - The type 'FakeAccount' must be 'base', 'final' or 'sealed' because
the supertype 'Account' is 'base'.

Faking a concrete class in tests

Because every class has an interface, you can replace a dependency in tests even if its author never declared an abstract interface for it. Here RateClient makes HTTP requests and PriceConverter depends on it directly:

// file: rates.dart
import 'dart:convert';
import 'dart:io';

class RateClient {
  RateClient(this.baseUrl) : _http = HttpClient() {
    print('RateClient(): opening an HttpClient');
  }

  final String baseUrl;
  final HttpClient _http;

  Future<double> rate(String from, String to) async {
    final req = await _http.getUrl(Uri.parse('$baseUrl/$from/$to'));
    final res = await req.close();
    return double.parse(await res.transform(utf8.decoder).join());
  }

  void close() => _http.close();
}

class PriceConverter {
  PriceConverter(this._rates);
  final RateClient _rates;

  Future<String> convert(double amount, String from, String to) async {
    final r = await _rates.rate(from, to);
    return '${(amount * r).toStringAsFixed(2)} $to';
  }
}

The test lives in a different library, so it implements only the public members:

// file: converter_test.dart
import 'rates.dart';

// No network, no HttpClient, and RateClient's constructor never runs.
class FakeRateClient implements RateClient {
  final calls = <String>[];

  @override
  String get baseUrl => 'fake://';

  @override
  Future<double> rate(String from, String to) async {
    calls.add('$from->$to');
    return 4.0;
  }

  @override
  void close() {}
}

Future<void> main() async {
  final fake = FakeRateClient();
  final converter = PriceConverter(fake);
  print(await converter.convert(25, 'USD', 'PLN'));
  print(await converter.convert(1.5, 'EUR', 'PLN'));
  print(fake.calls);
}

Output:

100.00 PLN
6.00 PLN
[USD->PLN, EUR->PLN]

The RateClient() message never appears: the fake doesn't run the real constructor. If the fake lived in rates.dart itself, the analyzer would also demand an implementation of the private _http getter.

This works, but it's coupling to a concrete class. If RateClient later gains a public member, every fake stops compiling. For dependencies you control, declaring a small abstract interface class is cleaner; see Dependency injection. When a fake needs only a couple of members of a large interface, noSuchMethod can fill in the rest, as shown in Composition and delegation.

Generic interfaces

A generic class defines a generic interface. An implementation can stay generic, or implement one specific instantiation:

class Box<T> {
  Box(this.value);
  final T value;
  String describe() => 'Box($value)';
}

// Generic implementation: still generic over T.
class LazyBox<T> implements Box<T> {
  LazyBox(this._compute);
  final T Function() _compute;
  late final T _value = _compute();

  @override
  T get value => _value;

  @override
  String describe() => 'LazyBox($value)';
}

// Implementing one specific instantiation.
class ZeroBox implements Box<int> {
  @override
  int get value => 0;

  @override
  String describe() => 'ZeroBox';
}

int doubled(Box<int> b) => b.value * 2;

void main() {
  final lazy = LazyBox(() {
    print('computing...');
    return 21;
  });
  print('created');
  print(doubled(lazy));
  print(doubled(lazy));
  print(doubled(ZeroBox()));

  final Object z = ZeroBox();
  print(z is Box<int>);
  print(z is Box<num>);
  print(z is Box<String>);
}

Output:

created
computing...
42
42
0
true
true
false

LazyBox satisfies the final T value field with a late final field behind a getter, so the value is computed once, on first use. ZeroBox is a Box<int>, and since Dart generics are covariant, also a Box<num>. See Generics for more.

Partial implementations: abstract classes and mixins

Only a concrete class has to implement everything. An abstract class can implement an interface, provide some members and leave the rest to subclasses. A mixin can do the same:

abstract interface class Shape {
  String get name;
  double get area;
  String describe();
}

// An abstract class may implement an interface only partially.
abstract class NamedShape implements Shape {
  @override
  String describe() => '$name with area ${area.toStringAsFixed(2)}';
}

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

  @override
  String get name => 'square';

  @override
  double get area => side * side;
}

// A mixin can also implement an interface and provide part of it.
mixin Loud implements Shape {
  @override
  String describe() => '${name.toUpperCase()}!!! AREA ${area.round()}!!!';
}

class Circle with Loud {
  Circle(this.r);
  final double r;

  @override
  String get name => 'circle';

  @override
  double get area => 3.14159 * r * r;
}

void main() {
  final shapes = <Shape>[Square(1.5), Circle(2)];
  for (final s in shapes) {
    print(s.describe());
  }
}

Output:

square with area 2.25
CIRCLE!!! AREA 13!!!

Square and Circle never mention Shape, yet both are Shapes: the interface is inherited through NamedShape and Loud. This is the classic "skeletal implementation" pattern: an interface for callers, plus an abstract base or mixin that implements the boring parts in terms of a few abstract ones.

abstract interface class is the Dart 3 idiom for a pure interface. abstract stops it from being instantiated, and interface stops other libraries from extending it, so code outside your library can depend only on the member signatures, never on inherited implementation. Keep in mind that adding a member to such an interface is still a breaking change: every existing implementation stops compiling until it adds the member.

Implementing SDK interfaces

Many SDK types are designed to be implemented. Two of the most common are Comparable<T>, which List.sort and generic algorithms rely on, and Exception, which marks a class as an expected, catchable error (see Custom exception). Enums can implement interfaces too:

class Version implements Comparable<Version> {
  const Version(this.major, this.minor, this.patch);

  final int major, minor, patch;

  @override
  int compareTo(Version other) {
    if (major != other.major) return major.compareTo(other.major);
    if (minor != other.minor) return minor.compareTo(other.minor);
    return patch.compareTo(other.patch);
  }

  @override
  String toString() => '$major.$minor.$patch';
}

enum Size implements Comparable<Size> {
  small(1),
  medium(5),
  large(10);

  const Size(this.liters);
  final int liters;

  @override
  int compareTo(Size other) => liters.compareTo(other.liters);
}

T maxOf<T extends Comparable<T>>(List<T> items) =>
    items.reduce((a, b) => a.compareTo(b) >= 0 ? a : b);

class ParseFailure implements Exception {
  ParseFailure(this.input);
  final String input;

  @override
  String toString() => 'ParseFailure: cannot parse "$input"';
}

void main() {
  final versions = [
    const Version(1, 10, 0),
    const Version(1, 2, 3),
    const Version(2, 0, 0),
    const Version(1, 2, 10),
  ];
  versions.sort();
  print(versions);
  print(maxOf(versions));
  print(maxOf([Size.medium, Size.large, Size.small]));

  try {
    throw ParseFailure('1.x');
  } on Exception catch (e) {
    print(e);
  }
}

Output:

[1.2.3, 1.2.10, 1.10.0, 2.0.0]
2.0.0
Size.large
ParseFailure: cannot parse "1.x"

versions.sort() with no comparator works because Version is Comparable. The bound T extends Comparable<T> on maxOf accepts both the class and the enum. More on ordering in Sorting and Equality and comparison.

Big interfaces: extend or mix in instead

Some SDK interfaces are large. Iterable<T> has about 30 members, and implementing it directly means writing every one:

class Countdown implements Iterable<int> {
  Countdown(this.from);
  final int from;

  @override
  Iterator<int> get iterator => List.generate(from, (i) => from - i).iterator;
}
error - Missing concrete implementations of 'Iterable.any', 'Iterable.cast',
'Iterable.contains', 'Iterable.elementAt', and 25 more.

Iterable is declared as an abstract mixin class, so you can extend it or mix it in (as IterableMixin from dart:collection) and get all the other members implemented in terms of iterator:

import 'dart:collection';

// Iterable is an `abstract mixin class`: extend it and only `iterator`
// is required. The other 29 members come from Iterable itself.
class Countdown extends Iterable<int> {
  Countdown(this.from);
  final int from;

  @override
  Iterator<int> get iterator => _CountdownIterator(from);
}

class _CountdownIterator implements Iterator<int> {
  _CountdownIterator(this._next);
  int _next;
  int? _current;

  @override
  int get current => _current!;

  @override
  bool moveNext() {
    if (_next <= 0) return false;
    _current = _next--;
    return true;
  }
}

// When you already extend something else, mix the implementation in.
class Base {
  String describe() => 'base';
}

class Evens extends Base with IterableMixin<int> {
  Evens(this.limit);
  final int limit;

  @override
  Iterator<int> get iterator =>
      [for (var i = 0; i <= limit; i += 2) i].iterator;
}

void main() {
  final c = Countdown(5);
  print(c.toList());
  print(c.where((n) => n.isOdd).join(', '));
  print(c.first);

  final e = Evens(10);
  print(e.map((n) => n * n).toList());
  print('${e.describe()} ${e.length}');
}

Output:

[5, 4, 3, 2, 1]
5, 3, 1
5
[0, 4, 16, 36, 64, 100]
base 6

Iterator<int>, on the other hand, is small (current and moveNext), so _CountdownIterator just implements it. The same split exists for other collections: ListBase/ListMixin, MapBase/MapMixin and SetBase/SetMixin in dart:collection.

Types you can't implement

A few core types are off limits, because the VM and compilers rely on knowing every implementation:

class MyInt implements int {}
class MyString implements String {}
class MyBool implements bool {}
class MyFn implements Function {}
class MyRecord implements Record {}
class MyEnum implements Enum {}
error - Classes and mixins can't implement 'int'. - subtype_of_disallowed_type
error - Classes and mixins can't implement 'String'. - subtype_of_disallowed_type
error - Classes and mixins can't implement 'bool'. - subtype_of_disallowed_type
error - The class 'Function' can't be implemented outside of its library
because it's a final class. - invalid_use_of_type_outside_library
error - Classes and mixins can't implement 'Record'. - subtype_of_disallowed_type
error - Concrete classes can't have 'Enum' as a superinterface.
- concrete_class_has_enum_superinterface

The same applies to double, num and Null. To give a value like a String its own type, use an extension type instead (see Composition and delegation).

Controlling who can implement your class

By default, any library may implement any class you publish. That means every public member you add later is a potential breaking change for someone's implements, and every private member you rely on is a potential NoSuchMethodError. Dart 3 class modifiers let you decide, for code outside your library:

Declaration Can be implemented Can be extended
class yes yes
interface class yes no
abstract interface class yes (can't be constructed) no
base class no yes (subclass must be base, final or sealed)
final class no no
sealed class no no

Rules of thumb:

The full table, including mixins and sealed hierarchies, is in Inheritance.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents