Nested classes

suggest change

Dart has no nested classes. Java has static nested classes, inner classes and anonymous classes, Kotlin and C# have their own versions, and in Dart you can't declare a class inside another class at all:

class LinkedList {
  class Node {
    int value;
    Node(this.value);
  }
}
main.dart:2:3: Error: Classes can't be declared inside other classes.
Try moving the class to the top-level.
  class Node {
  ^^^^^

You don't lose much, though. People nest classes for a few reasons, and Dart covers each one with a different feature:

Why you'd nest a class Dart alternative
hide a helper class (private static class Node) a top-level class whose name starts with _
let the helper see the outer class's private members library privacy: everything in one file shares private access
keep a big class and its helpers in separate files part files
an inner class that holds a reference to its outer object pass the outer object to the constructor
a namespace like Outer.Inner naming conventions, import prefixes, static members
a family of subclasses (sealed class Result { class Ok; class Err }) a sealed class with top-level subclasses
a small data holder used by one class records
a typed view over part of the outer data extension types
anonymous classes (new Listener() { ... }) closures and function types

The rest of this article goes through them one at a time.

Private helper classes and library privacy

In Java, privacy is per class, so a helper class has to be nested to see the outer class's private fields. In Dart, privacy is per library. A library is usually one file, and a name that starts with _ is visible everywhere in that file and nowhere else. See Libraries and visibility.

That makes a top-level _Node class in the same file the direct equivalent of a private static class Node:

// stack.dart

// The "nested" class: private to this file.
class _Node<T> {
  final T value;
  final _Node<T>? next;
  _Node(this.value, this.next);
}

class Stack<T> {
  _Node<T>? _top;
  int _length = 0;

  void push(T value) {
    _top = _Node(value, _top);
    _length++;
  }

  T pop() {
    final top = _top;
    if (top == null) throw StateError('stack is empty');
    _top = top.next;
    _length--;
    return top.value;
  }

  bool get isEmpty => _top == null;
  int get length => _length;
}
// main.dart
import 'stack.dart';

void main() {
  final stack = Stack<String>()
    ..push('a')
    ..push('b')
    ..push('c');
  print(stack.length);
  while (!stack.isEmpty) {
    print(stack.pop());
  }
}

Output:

3
c
b
a

Code in another file can use Stack, but it can't see _Node or any of Stack's private members:

import 'stack.dart';

void main() {
  final node = _Node(1, null);
  print(Stack<int>()._top);
}
error - bad.dart:4:16 - The function '_Node' isn't defined. ...
error - bad.dart:5:22 - The getter '_top' isn't defined for the type 'Stack<int>'. ...

The difference from Java: privacy protects the file, not the class. _Node can read Stack._top, and so can any other function in stack.dart. If a file starts to feel too big for that, split it into several libraries (or use part files, below).

Inner classes that need the outer object

A Java inner (non-static) class gets a hidden reference to the outer instance, so it can write items[i] and mean RingBuffer.this.items[i]. Dart has no hidden reference, so you pass the outer object to the constructor yourself. Since both classes live in the same library, the helper can still read the outer object's private fields.

The classic case is an iterator:

class RingBuffer<T> extends Iterable<T> {
  final List<T?> _items;
  int _start = 0;
  int _count = 0;
  int _modCount = 0;

  RingBuffer(int capacity) : _items = List.filled(capacity, null);

  void add(T value) {
    final end = (_start + _count) % _items.length;
    _items[end] = value;
    if (_count == _items.length) {
      _start = (_start + 1) % _items.length; // overwrite the oldest
    } else {
      _count++;
    }
    _modCount++;
  }

  @override
  Iterator<T> get iterator => _RingIterator(this);
}

// Java would make this a non-static inner class.
// In Dart the "outer" object is passed in explicitly.
class _RingIterator<T> implements Iterator<T> {
  final RingBuffer<T> _ring;
  final int _expectedModCount;
  int _index = -1;

  _RingIterator(this._ring) : _expectedModCount = _ring._modCount;

  @override
  bool moveNext() {
    if (_ring._modCount != _expectedModCount) {
      throw ConcurrentModificationError(_ring);
    }
    _index++;
    return _index < _ring._count;
  }

  @override
  T get current => _ring._items[(_ring._start + _index) % _ring._items.length] as T;
}

void main() {
  final ring = RingBuffer<int>(3);
  for (var i = 1; i <= 5; i++) {
    ring.add(i);
  }
  print(ring.toList());
  print(ring.map((x) => x * 10).join(', '));

  try {
    for (final x in ring) {
      ring.add(x);
    }
  } on ConcurrentModificationError catch (e) {
    print('error: ${e.runtimeType}');
  }
}

Output:

[3, 4, 5]
30, 40, 50
error: ConcurrentModificationError

_RingIterator reads _ring._items, _ring._start and _ring._modCount directly. In Java those reads would only compile if the iterator were nested inside RingBuffer. Here they compile because both classes are in the same file. Writing _ring. explicitly also makes it obvious which object the helper is touching. See Iterators for more on implementing Iterator.

Splitting a library with part files

Once the helpers get big you may want them in their own files without making them public. A part file is physically separate but belongs to the main library, so it shares the library's private names:

// lib/inventory.dart
library;

import 'dart:collection';

part 'inventory_entry.dart';

class Inventory {
  final _entries = SplayTreeMap<String, _Entry>();

  void add(String sku, int quantity) {
    final entry = _entries.putIfAbsent(sku, () => _Entry(sku));
    entry._quantity += quantity;
  }

  bool remove(String sku, int quantity) =>
      _entries[sku]?._take(quantity) ?? false;

  void report() {
    for (final e in _entries.values) {
      print(e);
    }
  }
}
// lib/inventory_entry.dart
part of 'inventory.dart';

// Private to the library, but lives in its own file.
class _Entry {
  final String sku;
  int _quantity = 0;

  _Entry(this.sku);

  bool _take(int n) {
    if (n > _quantity) return false;
    _quantity -= n;
    return true;
  }

  @override
  String toString() => '$sku: $_quantity';
}
// main.dart
import 'lib/inventory.dart';

void main() {
  final inv = Inventory()
    ..add('widget', 10)
    ..add('gadget', 3)
    ..add('widget', 5);
  print(inv.remove('gadget', 5));
  print(inv.remove('widget', 4));
  inv.report();
}

Output:

false
true
gadget: 3
widget: 11

Rules for parts:

The Dart team recommends small libraries over parts for hand-written code. Parts are mostly used by code generators (json_serializable, freezed and others generate *.g.dart part files so the generated code can reach your private members). For hand-written code, use them when several classes really need each other's private members. Otherwise, put each class in its own library and export them together. See Libraries.

Namespaces: Outer.Inner without nesting

In Java, Map.Entry and AlertDialog.Builder use the outer class as a namespace. Dart has three ways to get the same effect.

1. Name prefixes

The Dart convention is to fold the outer name into the class name. The SDK does it everywhere: Java's Map.Entry is MapEntry in Dart, and dart:io has HttpClient, HttpClientRequest and HttpClientResponse. A Pizza.Builder becomes PizzaBuilder.

2. Import prefixes

When two libraries define the same short name, import them with a prefix. The prefix acts as a namespace at the use site:

// lib/tree.dart
class Node {
  final String label;
  final List<Node> children;
  Node(this.label, [this.children = const []]);
}

class Visitor {
  void visit(Node node, [int depth = 0]) {
    print('${'  ' * depth}${node.label}');
    for (final child in node.children) {
      visit(child, depth + 1);
    }
  }
}
// lib/graph.dart
class Node {
  final int id;
  final Set<int> edges = {};
  Node(this.id);
}
// main.dart
import 'lib/tree.dart' as tree;
import 'lib/graph.dart' as graph;

void main() {
  final root = tree.Node('root', [
    tree.Node('a', [tree.Node('a1')]),
    tree.Node('b'),
  ]);
  tree.Visitor().visit(root);

  final n = graph.Node(1)..edges.addAll([2, 3]);
  print('graph node ${n.id} -> ${n.edges}');
  print(root.runtimeType);
  print(n.runtimeType);
}

Output:

root
  a
    a1
  b
graph node 1 -> {2, 3}
Node
Node

tree.Node reads a lot like a nested class, but the namespace is chosen by the importing file, not by the declaring one. At run time both classes are just Node. See Specifying a library prefix and Importing only part of a library.

3. Static members and named factories

Static members are reached through the class name, so they give you Outer.something syntax for constants, helper functions and constructors. A neat trick is a redirecting factory constructor that forwards to a private class. Callers write Shape.circle(...), like a Java static nested class, and the implementation classes stay hidden:

import 'dart:math' as math;

abstract class Shape {
  // Redirecting factories: callers write Shape.circle(...), the
  // implementation classes stay private to this library.
  const factory Shape.circle(double radius) = _Circle;
  const factory Shape.rect(double width, double height) = _Rect;

  double get area;
}

class _Circle implements Shape {
  final double radius;
  const _Circle(this.radius);

  @override
  double get area => math.pi * radius * radius;

  @override
  String toString() => 'circle(r=$radius)';
}

class _Rect implements Shape {
  final double width, height;
  const _Rect(this.width, this.height);

  @override
  double get area => width * height;

  @override
  String toString() => 'rect(${width}x$height)';
}

void main() {
  const shapes = [Shape.circle(1), Shape.rect(2, 3)];
  for (final s in shapes) {
    print('$s area=${s.area.toStringAsFixed(2)}');
  }
}

Output:

circle(r=1.0) area=3.14
rect(2.0x3.0) area=6.00

Because the factories are const, Shape.circle(1) can even be used in a constant list.

Nested enums and constants become a top-level enum next to the class plus static const fields. For a pure namespace of constants and functions, use an abstract final class. It can't be instantiated, extended or implemented:

// Java: class Order { enum Status { ... } static final int MAX_ITEMS = 50; }
enum OrderStatus {
  pending,
  shipped,
  delivered;

  bool get isFinal => this == delivered;
}

class Order {
  static const maxItems = 50;

  final int id;
  OrderStatus status = OrderStatus.pending;

  Order(this.id);

  void advance() {
    if (status.isFinal) return;
    status = OrderStatus.values[status.index + 1];
  }
}

// A pure namespace: can't be instantiated, extended or implemented.
abstract final class Http {
  static const ok = 200;
  static const notFound = 404;
  static const defaultTimeout = Duration(seconds: 30);

  static bool isSuccess(int code) => code >= 200 && code < 300;
}

void main() {
  final order = Order(1);
  print('max items: ${Order.maxItems}');
  for (var i = 0; i < 4; i++) {
    print('${order.status.name} final=${order.status.isFinal}');
    order.advance();
  }

  print(Http.isSuccess(Http.ok));
  print(Http.isSuccess(Http.notFound));
  print(Http.defaultTimeout.inSeconds);
}

Output:

max items: 50
pending final=false
shipped final=false
delivered final=true
delivered final=true
true
false
30

Http() is rejected with Abstract classes can't be instantiated. Many Dart style guides prefer plain top-level constants and functions, imported with a prefix, over a class that holds only statics. Use the class when the grouping makes call sites clearer. See Static members and Basic usage of enums.

Sealed class families

Kotlin and Swift often nest the cases of a closed hierarchy inside the base type (sealed class Result { class Ok; class Err }). In Dart the subclasses are top-level classes in the same library as a sealed base class. The compiler knows the full list of subtypes, so it checks that a switch handles every one:

sealed class Shape {
  const Shape();
}

final class Circle extends Shape {
  final double radius;
  const Circle(this.radius);
}

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

final class Triangle extends Shape {
  final double base, height;
  const Triangle(this.base, this.height);
}

double area(Shape shape) => switch (shape) {
      Circle(:final radius) => 3.14159 * radius * radius,
      Square(:final side) => side * side,
      Triangle(:final base, :final height) => base * height / 2,
    };

void main() {
  const shapes = [Circle(1), Square(2), Triangle(3, 4)];
  for (final s in shapes) {
    print('${s.runtimeType}: ${area(s)}');
  }
}

Output:

Circle: 3.14159
Square: 4.0
Triangle: 6.0

Delete the Triangle case and the code no longer compiles:

error - bad.dart:20:29 - The type 'Shape' isn't exhaustively matched by the switch cases since it doesn't match the pattern 'Triangle()'. Try adding a wildcard pattern or cases that match 'Triangle()'. - non_exhaustive_switch_expression

A sealed class can only be extended inside its own library (its file plus any parts), which is the guarantee nesting gives you in other languages. If the short names might clash, prefix them (ShapeCircle) or import the library with a prefix (shapes.Circle). See Pattern matching.

Records instead of small data classes

Classes often nest a tiny holder like private static class Stats { int total; int unique; } just to return several values or to type a collection element. In Dart, a record type can be written inline in a signature, with no declaration at all. When a shape is used in several places, give it a name with typedef:

// Java: public static class Hit { String path; int count; }
typedef PageHit = ({String path, int count});

class AccessLog {
  final _hits = <String, int>{};

  void record(String path) => _hits.update(path, (n) => n + 1, ifAbsent: () => 1);

  // An inline record type instead of a nested Stats class.
  ({int total, int unique, PageHit? top}) stats() {
    PageHit? top;
    for (final MapEntry(key: path, value: count) in _hits.entries) {
      if (top == null || count > top.count) top = (path: path, count: count);
    }
    final total = _hits.values.fold(0, (a, b) => a + b);
    return (total: total, unique: _hits.length, top: top);
  }
}

void main() {
  final log = AccessLog();
  for (final p in ['/', '/about', '/', '/blog', '/']) {
    log.record(p);
  }

  final s = log.stats();
  print(s);
  print('top page: ${s.top?.path}');

  final (:total, :unique, top: _) = log.stats();
  print('$total hits on $unique pages');
}

Output:

(top: (count: 3, path: /), total: 5, unique: 3)
top page: /
5 hits on 3 pages

Records come with ==, hashCode and toString for free, and they can be destructured. A typedef has to be top-level too, and you can make it private (typedef _Hit = ...) when only the library uses it. Don't use a private typedef in a public signature like stats(), though: the library_private_types_in_public_api lint flags that, because callers can't name the type. See Structs, tuples, and records.

Extension types as nested views

Sometimes the "inner classes" are typed accessors over parts of one data structure, such as Order.Customer and Order.LineItem over a decoded JSON document. Extension types handle this well. Each one is a compile-time view over an existing object, so you get typed getters for every level of the JSON without allocating any wrapper objects:

import 'dart:convert';

// Typed views over nested JSON, with no wrapper objects at run time.
extension type Order(Map<String, Object?> json) {
  int get id => json['id'] as int;
  Customer get customer => Customer(json['customer'] as Map<String, Object?>);
  Iterable<LineItem> get items =>
      (json['items'] as List).map((e) => LineItem(e as Map<String, Object?>));
  num get total => items.fold<num>(0, (sum, i) => sum + i.subtotal);
}

extension type Customer(Map<String, Object?> json) {
  String get name => json['name'] as String;
}

extension type LineItem(Map<String, Object?> json) {
  String get sku => json['sku'] as String;
  int get qty => json['qty'] as int;
  num get price => json['price'] as num;
  num get subtotal => qty * price;
}

const source = '''
{"id": 42, "customer": {"name": "Ada"},
 "items": [{"sku": "pen", "qty": 3, "price": 1.5},
           {"sku": "pad", "qty": 1, "price": 4}]}
''';

void main() {
  final order = Order(jsonDecode(source) as Map<String, Object?>);
  print('order ${order.id} for ${order.customer.name}');
  for (final item in order.items) {
    print('  ${item.sku} x${item.qty} = ${item.subtotal}');
  }
  print('total: ${order.total}');
  print(order.customer.runtimeType);
}

Output:

order 42 for Ada
  pen x3 = 4.5
  pad x1 = 4
total: 8.5
_Map<String, dynamic>

The last line shows that at run time a Customer is just the underlying map. Extension types give you type checking and no run-time cost, but no run-time identity: is Customer can't tell a Customer from any other map. Use real classes when you need validation at construction time or a separate run-time type. See JSON.

Anonymous classes: closures and function types

Java code often creates throwaway objects like new Comparator<String>() { ... } or new Listener() { ... }. Dart has no anonymous classes, and usually doesn't need them:

abstract interface class JobListener {
  void onStart(String job);
  void onDone(String job, Duration took);
}

// Stands in for Java's "new JobListener() { ... }":
// an adapter that implements the interface with closures.
class _FnListener implements JobListener {
  final void Function(String) _onStart;
  final void Function(String, Duration) _onDone;
  _FnListener(this._onStart, this._onDone);

  @override
  void onStart(String job) => _onStart(job);
  @override
  void onDone(String job, Duration took) => _onDone(job, took);
}

class Runner {
  final _listeners = <JobListener>[];

  void addListener(JobListener l) => _listeners.add(l);

  void listen({
    void Function(String job)? onStart,
    void Function(String job, Duration took)? onDone,
  }) =>
      addListener(_FnListener(onStart ?? (_) {}, onDone ?? (_, _) {}));

  void run(String job) {
    for (final l in _listeners) {
      l.onStart(job);
    }
    for (final l in _listeners) {
      l.onDone(job, const Duration(milliseconds: 120));
    }
  }
}

void main() {
  var finished = 0; // closures capture local variables, like inner classes

  final runner = Runner()
    ..listen(onStart: (job) => print('start $job'))
    ..listen(onDone: (job, took) {
      finished++;
      print('done $job in ${took.inMilliseconds} ms');
    });

  runner.run('backup');
  runner.run('report');
  print('finished: $finished');

  // Single-method interfaces are just function types.
  final words = ['pear', 'fig', 'banana'];
  words.sort((a, b) => a.length.compareTo(b.length));
  print(words);
}

Output:

start backup
done backup in 120 ms
start report
done report in 120 ms
finished: 2
[fig, pear, banana]

Unlike a Java anonymous class, which can only read effectively-final locals, a Dart closure can modify the variables it captures (finished++). Callers that want a full object can still implement JobListener and pass it to addListener. The (_, _) parameter list relies on wildcard variables, available since Dart 3.7. See Lambdas and closures.

Summary

Feedback about page:

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



Table Of Contents