Primary constructors

suggest change

Dart 3.13 added primary constructors: a parameter list written right after the class name. That list is the class's main constructor, and it can declare fields too. This removes the most repetitive code in Dart classes, where every field name is written three times:

// Before Dart 3.13: every field is written three times.
class PointOld {
  final int x;
  final int y;

  PointOld(this.x, this.y);
}

// Dart 3.13: the parameter list after the class name is the constructor.
class Point(final int x, final int y);

void main() {
  final a = PointOld(1, 2);
  final b = Point(3, 4);
  print('${a.x}, ${a.y}');
  print('${b.x}, ${b.y}');
}

Output:

1, 2
3, 4

The two classes behave the same. Point has two final fields, x and y, and an unnamed constructor that sets them. A class with no members can end with ; instead of {}.

This article covers:

The examples were run with Dart 3.13.4. A package needs sdk: ^3.13.0 in pubspec.yaml to use primary constructors. With a lower minimum SDK, the analyzer reports This requires the 'primary-constructors' language feature to be enabled.

The classic constructor forms are explained in Constructors and Creating a class.

Declaring parameters

A parameter that starts with final or var is a declaring parameter. It declares a field with the same name and type and initializes it from the argument:

All parameter kinds work: required positional, optional positional, and named, with required and default values. Generic classes work too:

class Counter(final String label, var int count);

class User({
  required final String name,
  final int age = 0,
  final String? email,
});

class Size([final int width = 80, final int height = 24]);

class Pair<A, B>(final A first, final B second);

void main() {
  final c = Counter('clicks', 0);
  c.count++;
  print('${c.label}: ${c.count}');

  final u = User(name: 'Ann', email: 'ann@example.com');
  print('${u.name}, ${u.age}, ${u.email}');

  final s = Size(120);
  print('${s.width}x${s.height}');

  final p = Pair('answer', 42);
  print('${p.first} ${p.second} ${p.runtimeType}');
}

Output:

clicks: 1
Ann, 0, ann@example.com
120x24
answer 42 Pair<String, int>

The fields are ordinary fields. c.count++ works because count was declared with var. Assigning to u.name is a compile error ('name' can't be used as a setter because it's final).

Plain parameters

A parameter without final or var doesn't declare a field. It is an ordinary constructor parameter, and you can use it in field initializers in the class body. This is how you store a derived value instead of the raw argument:

class Temperature(double celsius) {
  final double fahrenheit = celsius * 9 / 5 + 32;
  final String label = '${celsius.toStringAsFixed(1)} C';
}

class Email(String raw) {
  final String address = raw.trim().toLowerCase();

  String get domain => address.split('@').last;
}

void main() {
  final t = Temperature(21.5);
  print('${t.label} = ${t.fahrenheit} F');

  final e = Email('  Ann@Example.COM ');
  print('${e.address} / ${e.domain}');
}

Output:

21.5 C = 70.7 F
ann@example.com / example.com

Before 3.13, this needed an initializer list (Temperature(double celsius) : fahrenheit = celsius * 9 / 5 + 32;). Now the field and its initial value sit together.

A plain parameter is only in scope in non-late field initializers and in the primary constructor's initializer list and body (see below). It isn't a field, so methods, getters and late field initializers can't see it:

class Temperature(double celsius) {
  final double fahrenheit = celsius * 9 / 5 + 32; // OK: field initializer

  late final double kelvin = celsius + 273.15; // error

  String describe() => '$celsius C'; // error
}

dart analyze reports:

  error - scope.dart:4:30 - Undefined name 'celsius'. Try correcting the name to one that is defined, or defining the name. - undefined_identifier
  error - scope.dart:6:26 - Undefined name 'celsius'. Try correcting the name to one that is defined, or defining the name. - undefined_identifier

If a method needs the value, make the parameter a declaring parameter (final double celsius). A late field initializer can use declaring parameters, because they are fields.

Initializer list and body: this : ... { ... }

The parameter list after the class name has no place for asserts, super(...) calls or a constructor body. You write those in the class body, after the keyword this:

class Range(final int start, final int end) {
  this : assert(start <= end, 'start must not be after end');

  int get length => end - start;
}

class Connection(final String host, final int port) {
  final List<String> log = [];

  this {
    log.add('created $host:$port');
  }
}

void main() {
  print(Range(2, 7).length);
  print(Connection('localhost', 5432).log);
  try {
    Range(5, 1);
  } on AssertionError catch (e) {
    print('AssertionError: ${e.message}');
  }
}

Output (run with dart run --enable-asserts):

5
[created localhost:5432]
AssertionError: start must not be after end

The form is this : initializer list { body }, where either part can be left out:

A class can have at most one such this part.

Superclasses, super. and this.

Super parameters and initializing formals work in primary constructors. A super parameter (super.name) passes the argument to the superclass constructor. To transform an argument first, take it as a plain parameter and call super(...) in the this : initializer list:

class Animal(final String name) {
  String describe() => 'animal $name';
}

// super.name forwards the argument to Animal's constructor.
class Dog(super.name, final String breed) extends Animal {
  @override
  String describe() => 'dog $name ($breed)';
}

// A plain parameter passed on through an explicit super call.
class Cat(String name) extends Animal {
  this : super(name.toUpperCase());
}

// this.x still works: the field is declared in the body.
class Account(this.id) {
  final String id;
  int balance = 0;
}

void main() {
  print(Dog('Rex', 'pug').describe());
  print(Cat('tom').describe());
  print(Account('acc-1').id);
}

Output:

dog Rex (pug)
animal TOM
acc-1

Use this.id with a separately declared field when the field needs a doc comment of its own, or should be listed with other fields in the body. Otherwise final String id in the header is shorter. More on calling superclass constructors is in Inheritance.

const and named primary constructors

Write const between class and the class name to make the primary constructor const. All fields must then be final. To give the primary constructor a name, write .name after the class name:

class const Color(final int r, final int g, final int b) {
  this : assert(r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255);

  static const black = Color(0, 0, 0);
  static const white = Color(255, 255, 255);

  String get hex =>
      '#${[r, g, b].map((c) => c.toRadixString(16).padLeft(2, '0')).join()}';
}

class Polar.fromDegrees(final double r, final double degrees);

void main() {
  print(Color.white.hex);
  print(identical(const Color(0, 0, 0), Color.black));
  final p = Polar.fromDegrees(1, 90);
  print('${p.r} ${p.degrees}');
}

Output:

#ffffff
true
1.0 90.0

class const Color(var int r, ...) is a compile error: Can't define a const constructor for a class with non-final fields. Const classes like this are a good basis for value objects; see Immutability.

Polar only has the named constructor Polar.fromDegrees. There is no unnamed Polar(...).

Other constructors: new and factory

Dart 3.13 also has a shorter way to write other constructors. Instead of repeating the class name, start a generative constructor with new and a factory constructor with factory:

Old syntax New syntax
Vec(...) new(...)
Vec.zero() : this(0, 0); new zero() : this(0, 0);
const Vec.zero() : ... const new zero() : ...
factory Vec.parse(String s) {...} factory parse(String s) {...}
factory Vec(String s) {...} factory(String s) {...}

A class with a primary constructor can have more constructors, but every other generative constructor must redirect to another constructor, eventually reaching the primary one. Factory constructors are unrestricted:

import 'dart:math';

class Vec(final double x, final double y) {
  // Redirecting generative constructors: `new` instead of `Vec`.
  new zero() : this(0, 0);
  new unit(double angle) : this(cos(angle), sin(angle));

  // Factory constructors: `factory` instead of `factory Vec`.
  factory parse(String s) {
    final [x, y] = s.split(',').map(double.parse).toList();
    return Vec(x, y);
  }

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

void main() {
  print(Vec(1, 2));
  print(Vec.zero());
  print(Vec.unit(0));
  print(Vec.parse('3.5,-1'));
}

Output:

Vec(1.0, 2.0)
Vec(0.0, 0.0)
Vec(1.0, 0.0)
Vec(3.5, -1.0)

A non-redirecting generative constructor next to a primary constructor is an error:

class Two(final int a) {
  Two.other(int v) : a = v;
}
  error - e9.dart:2:3 - Classes with primary constructors can't have non-redirecting generative constructors. Try making the constructor redirect to the primary constructor, or remove the primary constructor. - non_redirecting_generative_constructor_with_primary

This rule guarantees that every object goes through the primary constructor, so field initializers and the this body always run. If a class really needs several independent generative constructors, don't give it a primary constructor.

The new and factory forms also work in classes without a primary constructor. That is handy for a private constructor plus a caching factory:

// `new` and `factory` also work in classes without a primary constructor.
class Money {
  final int cents;
  final String currency;

  const new(this.cents, this.currency);
  const new zero(String currency) : this(0, currency);
  new dollars(double amount) : cents = (amount * 100).round(), currency = 'USD';

  @override
  String toString() => '$cents $currency';
}

class Logger {
  static final _cache = <String, Logger>{};
  final String name;

  new _(this.name);

  // An unnamed factory: no class name needed.
  factory(String name) => _cache.putIfAbsent(name, () => Logger._(name));
}

void main() {
  print(Money(250, 'EUR'));
  print(const Money.zero('PLN'));
  print(Money.dollars(1.99));
  print(identical(Logger('db'), Logger('db')));
}

Output:

250 EUR
0 PLN
199 USD
true

Callers don't change: they still write Money.zero('PLN'), Logger('db'), and so on. Renaming the class no longer means editing every constructor.

Enums and extension types

Enhanced enums can have a primary constructor too. Enum fields must be final, and the constructor is const without writing const:

enum Planet(final double massKg, final double radiusM) {
  mercury(3.303e23, 2.4397e6),
  earth(5.976e24, 6.37814e6),
  jupiter(1.9e27, 7.1492e7);

  double get surfaceGravity => 6.67300e-11 * massKg / (radiusM * radiusM);
}

enum Level(final int severity) {
  debug(10),
  info(20),
  error(40);

  bool operator >=(Level other) => severity >= other.severity;
}

void main() {
  for (final p in Planet.values) {
    print('${p.name}: ${p.surfaceGravity.toStringAsFixed(2)} m/s2');
  }
  print(Level.error >= Level.info);
}

Output:

mercury: 3.70 m/s2
earth: 9.80 m/s2
jupiter: 24.81 m/s2
true

enum Level(var int severity) is an error: Enums can only declare final fields. Basic enums are covered in Enums.

Extension types always had a primary-constructor-like header, extension type UserId(int value). It now follows the same rules as classes: const goes after extension type, final is allowed on the representation parameter, and other constructors can use new:

extension type const UserId(int value) {
  bool get isSystem => value < 1000;
}

extension type Celsius(final double degrees) {
  new fromFahrenheit(double f) : this((f - 32) * 5 / 9);
}

void main() {
  const id = UserId(42);
  print('${id.value} ${id.isSystem}');
  print(Celsius.fromFahrenheit(212).degrees);
}

Output:

42 true
100.0

Private declaring parameters

Since Dart 3.12, a named parameter can have a private name. Callers use the name without the underscore. This works for declaring parameters too, so private fields can be set through readable named arguments:

class Session({required final String _token, final int _ttl = 3600}) {
  bool get isShortLived => _ttl < 600;
  String get masked => '${_token.substring(0, 4)}...';
}

void main() {
  // Callers use the names without the underscore.
  final s = Session(token: 'abcd1234efgh', ttl: 300);
  print('${s.masked} ${s.isShortLived}');
}

Output:

abcd... true

Breaking change: no final or var on ordinary parameters

Because final and var now mean "declare a field" in a primary constructor, Dart 3.13 no longer allows them on ordinary function, method and closure parameters:

void greet(final String name, [var int times = 1]) {
  for (var i = 0; i < times; i++) {
    print('Hello, $name');
  }
}

final square = (final int n) => n * n;
  error - brk.dart:1:12 - Can't have modifier 'final' here. Try removing 'final'. - extraneous_modifier
  error - brk.dart:1:32 - Can't have modifier 'var' here. Try removing 'var'. - extraneous_modifier
  error - brk.dart:1:32 - Variables can't be declared using both 'var' and a type name. Try removing 'var.' - var_and_type
  error - brk.dart:7:17 - Can't have modifier 'final' here. Try removing 'final'. - extraneous_modifier

Some things to know:

dart fix --apply --code=extraneous_modifier

That turns the code above into void greet(String name, [int times = 1]) and (int n) => n * n.

Migrating existing classes with lints and dart fix

Two lints find classes that could use the new syntax:

Enable them in analysis_options.yaml:

linter:
  rules:
    - use_primary_constructors
    - use_declaring_parameters

Both have automatic fixes. Take this pre-3.13 code:

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

class Person {
  final String name;
  int age;
  Person({required this.name, this.age = 0}) : assert(name != '');
}

class Counter {
  int count = 0;
  final String label;
  Counter(this.label);
  void inc() => count++;
}

dart fix --apply first converts the constructors (use_primary_constructors) and then moves the fields into the header (use_declaring_parameters):

lib\a.dart
  use_declaring_parameters - 5 fixes
  use_primary_constructors - 3 fixes

8 fixes made in 1 file.

Result:

class const Point(final int x, final int y) {
}

class Person({required final String name, var int age = 0}) {
  this : assert(name != '');
}

class Counter(final String label) {
  int count = 0;
  void inc() => count++;
}

Notice that the assert moved into a this : initializer list, and that count, which has its own initial value, stayed in the body. You can then replace the empty { } of Point with ; by hand. To apply one step at a time, run dart fix --apply --code=use_primary_constructors first. That keeps this.x parameters with the fields in the body, which is useful when fields have doc comments you want to keep next to them.

What primary constructors don't do

A primary constructor only saves typing for the constructor and fields. It doesn't generate ==, hashCode or toString, like Kotlin data classes or C# records do:

class Config(final String host, final int port);

class Point(final int x, final int y) {
  @override
  bool operator ==(Object other) =>
      other is Point && other.x == x && other.y == y;

  @override
  int get hashCode => Object.hash(x, y);

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

void main() {
  print(Config('h', 1) == Config('h', 1));
  print(Config('h', 1));
  print(Point(1, 2) == Point(1, 2));
  print(Point(1, 2));
}

Output:

false
Instance of 'Config'
true
Point(1, 2)

If you only need to group a few values with structural equality, a record such as ({String host, int port}) may be enough. See Structs, tuples, and records and Equality and comparison.

Summary

Feedback about page:

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



Table Of Contents