Constructor parameter shorthands: this., super. and private named parameters
suggest changeMost constructors do the same few things: copy arguments into fields, and pass some arguments on to the superclass constructor. Dart has three shorthands for this:
- initializing formals:
this.xsets fieldxfrom the argument - super parameters (Dart 2.17):
super.xpasses the argument to the superclass constructor - private named parameters (Dart 3.12):
{this._x}sets the private field_x, and callers writex:
class Shape {
final String name;
final String color;
Shape(this.name, {this.color = 'black'});
}
class Circle extends Shape {
final double radius;
Circle(super.name, this.radius, {super.color});
}
class Label {
final String _text;
final int _size;
Label({required this._text, this._size = 12});
}
Each of these constructors would take two or three times as much code without the shorthands. This article covers the rules for each one, how they work with required, default values and named superclass constructors, the lints that point out where to use them, and how dart fix converts old code.
The examples were run with Dart 3.13.4. Private named parameters need sdk: ^3.12.0 or higher in pubspec.yaml. Super parameters need 2.17, which every null-safe package already has.
Initializing formals: this.x
A parameter written as this.name sets the field name to the argument before the constructor body runs. It works for every parameter kind: required positional, optional positional with [...], and named with {...}. You can combine it with required and default values:
class Server {
final String host;
final int port;
final bool secure;
final Duration timeout;
final String? name;
Server(
this.host, [
this.port = 80,
]) : secure = false,
timeout = const Duration(seconds: 30),
name = null;
Server.named({
required this.host,
this.port = 443,
this.secure = true,
this.timeout = const Duration(seconds: 10),
this.name,
});
}
void main() {
final a = Server('example.com');
final b = Server('example.com', 8080);
final c = Server.named(host: 'api.example.com', name: 'api');
for (final s in [a, b, c]) {
print('${s.host}:${s.port} secure=${s.secure} '
'timeout=${s.timeout.inSeconds}s name=${s.name}');
}
}
Output:
example.com:80 secure=false timeout=30s name=null
example.com:8080 secure=false timeout=30s name=null
api.example.com:443 secure=true timeout=10s name=api
Some rules to know:
- The parameter gets the field's type.
String this.hostis allowed, but thetype_init_formalslint flags it (Don't needlessly type annotate initializing formals). - A non-nullable named or optional
this.xneeds eitherrequiredor a default value. A nullable field likenamecan be left out, and it is set tonull. this.xcan be mixed with initializer list entries (secure = false), as long as no field is set twice.- Because the field is set before the body runs,
this.xworks forfinalfields. This is the main reason to prefer it over assigning in the body. The old Constructors article shows the body-assignment form, which needslatefields.
Scope: initializer list vs body
An initializing formal is also a final local variable that the initializer list can read, so you can compute other fields from it. In the constructor body, the name refers to the field:
class Range {
final int start;
final int end;
final int length;
// Initializing formals are in scope in the initializer list.
Range(this.start, this.end)
: assert(start <= end),
length = end - start {
// In the body, `start` is the field (the same value here).
print('Range($start, $end) length=$length');
}
}
class Counter {
int count;
Counter(this.count) {
count++; // assigns the field, not the parameter
}
}
void main() {
Range(3, 10);
print(Counter(5).count);
}
Output:
Range(3, 10) length=7
6
Where this.x isn't allowed
class Point {
final int x;
final int y;
Point(this.x, this.z);
factory Point.origin(this.x) => Point(0, 0);
Point.both(int v, this.x) : x = v, y = v;
}
dart analyze reports:
error - e1.dart:5:3 - All final variables must be initialized, but 'y' isn't. Try adding an initializer for the field. - final_not_initialized_constructor
error - e1.dart:5:17 - 'z' isn't a field in the enclosing class. Try correcting the name to match an existing field, or defining a field named 'z'. - initializing_formal_for_non_existent_field
error - e1.dart:7:24 - Initializing formal parameters can't be used in factory constructors. Try using a normal parameter. - field_initializer_factory_constructor
error - e1.dart:9:31 - Fields can't be initialized in both the parameter list and the initializers. Try removing one of the initializations. - field_initialized_in_parameter_and_initializer
A factory constructor doesn't create this; it returns an object. So it can only take plain parameters and pass them to a generative constructor. Redirecting constructors (: this(...)) can't use this.x either.
Super parameters: super.x
Constructors aren't inherited. A subclass constructor that takes values for the superclass has to accept them and pass them on. Before Dart 2.17, each forwarded parameter was written twice, with its type and default value copied from the superclass:
class Shape {
final String name;
final String color;
final double opacity;
Shape(this.name, {this.color = 'black', this.opacity = 1.0});
}
class Circle extends Shape {
final double radius;
// Before Dart 2.17: every forwarded parameter is written twice.
Circle.old(String name, this.radius, {String color = 'black', double opacity = 1.0})
: super(name, color: color, opacity: opacity);
// With super parameters.
Circle(super.name, this.radius, {super.color, super.opacity});
}
void main() {
final a = Circle.old('a', 1, color: 'red');
final b = Circle('b', 2, color: 'red');
final c = Circle('c', 3);
for (final s in [a, b, c]) {
print('${s.name} r=${s.radius} ${s.color} ${s.opacity}');
}
}
Output:
a r=1.0 red 1.0
b r=2.0 red 1.0
c r=3.0 black 1.0
A super parameter takes more from the superclass constructor than its value:
- The type.
super.nameis aStringbecauseShape'snameparameter is aString. You may write a narrower type, such asIntNum(int super.value)for anumparameter. - The default value.
{super.color}has no default of its own, so it uses'black'fromShape. That is whyCircle('c', 3)is black. Write{super.color = 'red'}to use a different default. requiredisn't inherited. If the superclass parameter is{required this.x}, a plain{super.x}is an error (The parameter 'x' can't have a value of 'null' because of its type, but the implicit default value is 'null'). Write{required super.x}.
Positional vs named forwarding
The two kinds of super parameters follow different rules:
- Named super parameters match by name.
super.atis passed asat:. - Positional super parameters match by position: the first positional
super.parameter becomes the first positional argument of the superclass constructor, the second becomes the second, and so on. The names don't matter, and other parameters can sit between them.
With an explicit super(...) or super.name(...) call in the initializer list, super parameters are added to that call:
class Event {
final String source;
final int id;
final DateTime? at;
final Map<String, Object?> data;
Event(this.source, this.id, {this.at, this.data = const {}});
Event.system(this.id, {this.at, this.data = const {}}) : source = 'system';
}
class Click extends Event {
final int x, y;
// Positional super parameters are passed in order: source, then id.
// Other parameters can sit between them.
Click(super.source, this.x, this.y, super.id, {super.at});
// Named super parameters can be mixed with named arguments in super(...).
Click.now(super.source, super.id, this.x, this.y)
: super(at: DateTime(2026, 10, 18));
// Super parameters forward to whichever constructor super.name(...) calls.
Click.system(super.id, {super.data}) : x = 0, y = 0, super.system();
}
void main() {
final c1 = Click('mouse', 10, 20, 1);
final c2 = Click.now('touch', 2, 5, 6);
final c3 = Click.system(3, data: {'reason': 'test'});
for (final c in [c1, c2, c3]) {
print('${c.source}#${c.id} (${c.x},${c.y}) at=${c.at} data=${c.data}');
}
}
Output:
mouse#1 (10,20) at=null data={}
touch#2 (5,6) at=2026-10-18 00:00:00.000 data={}
system#3 (0,0) at=null data={reason: test}
Click.system passes id as the first positional argument of Event.system, which is its id.
There is one restriction. You can't mix positional super parameters with positional arguments in the explicit call, because then it isn't clear which position each one takes:
class Click extends Event {
Click(super.source, int id) : super(id);
}
error - e2.dart:8:15 - Positional super parameters can't be used when the super constructor invocation has a positional argument. Try making all the positional parameters passed to the super constructor be either all super parameters or all normal parameters. - positional_super_formal_parameter_with_positional_argument
Either make both parameters super parameters (Click(super.source, super.id)), or make both plain and pass them explicitly (Click(String source, int id) : super(source, id)). The explicit form is also what you need to transform a value first, like super(name.toUpperCase()); see Inheritance.
Matching names by position: a trap
Since positional super parameters match by position, swapping their names still compiles. Each one silently takes the type of the superclass parameter at its position:
class Event {
final String source;
final int id;
Event(this.source, this.id);
}
class Key extends Event {
Key(super.id, super.source); // names swapped, but still compiles
}
void main() {
final k = Key('keyboard', 7);
print('source=${k.source} id=${k.id}');
}
Output:
source=keyboard id=7
The program works, but anyone reading Key(super.id, super.source) would expect the first argument to be the id. The matching_super_parameters lint catches it:
info - e3.dart:9:7 - The super parameter named 'id'' does not share the same name as the corresponding parameter in the super constructor, 'source'. Try using the name of the corresponding parameter in the super constructor. - matching_super_parameters
info - e3.dart:9:17 - The super parameter named 'source'' does not share the same name as the corresponding parameter in the super constructor, 'id'. Try using the name of the corresponding parameter in the super constructor. - matching_super_parameters
Private named parameters: {this._x}
Fields are often private, with a public getter or no getter at all. Positional this._x has always worked. Named parameters, however, couldn't start with _ before Dart 3.12, because the name is part of the API that callers use. So a private field set from a named argument needed a plain parameter plus an initializer list entry.
Dart 3.12 lets an initializing formal have a private name. Callers use the name without the underscore:
class Account {
final String _id;
int _balance;
final List<String> _history;
// Before Dart 3.12: private fields need plain parameters and an initializer list.
Account.old({required String id, int balance = 0})
: _id = id,
_balance = balance,
_history = [];
// Dart 3.12: private named initializing formals. Callers write id: and balance:.
Account({required this._id, this._balance = 0}) : _history = [];
String get id => _id;
int get balance => _balance;
void deposit(int amount) {
_balance += amount;
_history.add('+$amount');
}
@override
String toString() => 'Account($_id, $_balance, $_history)';
}
Used from another library:
import 'package:ctorsh/account.dart';
void main() {
final a = Account(id: 'acc-1', balance: 100);
a.deposit(50);
print(a);
print(Account.old(id: 'acc-2'));
print(Account(id: 'acc-3'));
}
Output:
Account(acc-1, 150, [+50])
Account(acc-2, 0, [])
Account(acc-3, 0, [])
The two constructors look exactly the same to callers. required and default values work as usual. Writing the private name at the call site is an error, even inside the same library:
error - e4.dart:20:5 - The named parameter '_x' should use the corresponding public name 'x' at the callsite. Try changing the name to 'x'. - undefined_named_parameter
Rules for private named parameters
The feature only applies to parameters that initialize a field. Other uses of a leading underscore are errors:
class A {
final int _x;
final int _y;
final int _1;
A({required this._x, required this._y, int y = 0, this._1 = 0});
}
void f({int _flag = 0}) {}
error - e4.dart:5:38 - The corresponding public name 'y' is already the name of another parameter. Try renaming one of the parameters. - private_named_parameter_duplicate_public_name
error - e4.dart:5:58 - A private named parameter must be a public identifier after removing the leading underscore. - private_named_parameter_without_public_name
error - e4.dart:8:13 - Named parameters that don't refer to instance variables can't start with underscore. - private_named_non_field_parameter
In short:
- only
this._x(andfinal/vardeclaring parameters in a primary constructor) can be private and named. A plain{int _flag}can't. - the name without
_must be a valid public identifier:_1would become1, which isn't one - two parameters can't end up with the same public name
Super parameters and private names
The public name is the parameter's real name, so subclasses forward it like any other named parameter, using the public name: super.title, not super._title. This also works from another library, which can't see the private field:
// lib/widget.dart
class Panel {
final String _title;
final int _padding;
const Panel({required this._title, this._padding = 8});
String describe() => 'Panel($_title, $_padding)';
}
import 'package:ctorsh/widget.dart';
// A subclass in another library: super.title forwards to Panel's
// private named parameter, whose public name is `title`.
class Card extends Panel {
final bool raised;
const Card({required super.title, super.padding, this.raised = false});
}
void main() {
print(const Card(title: 'Settings', raised: true).describe());
}
Output:
Panel(Settings, 8)
Card didn't repeat the default for padding; it took 8 from Panel. super._title is an error (No associated named super constructor parameter).
How the shorthands combine with primary constructors
Dart 3.13 added primary constructors, where final/var parameters after the class name declare fields. All three shorthands work there too:
class Animal(final String name);
class Dog(super.name, final String breed) extends Animal;
class Session({required final String _token, final int _ttl = 3600});
super.name forwards to Animal, and final String _token is a private field set with token:. If a field is declared in the body (for example because it has its own doc comment), this.x in the primary constructor still works. Extension types have a similar header for their representation value; they are covered in the Extension types article.
Lints and dart fix
Four lints help with this. Enable them in analysis_options.yaml:
linter:
rules:
- prefer_initializing_formals
- use_super_parameters
- matching_super_parameters
- type_init_formals
prefer_initializing_formalsflagsfield = paraminitializer entries and body assignments that could bethis.field. On Dart 3.12+ libraries it also flags private fields set from named parameters (_text = text). In a package with a lower minimum SDK, where{this._text}isn't allowed, it stays quiet about those.use_super_parametersflags parameters that are only passed on tosuper(...).matching_super_parametersflags positional super parameters whose names don't match the superclass parameters.type_init_formalsflags redundant types onthis.x.
The first two have automatic fixes. Here is pre-2.17 code:
class Shape {
final String name;
final String color;
Shape(String name, {String color = 'black'})
: name = name,
color = color;
}
class Circle extends Shape {
final double radius;
Circle(String name, double radius, {String color = 'black'})
: radius = radius,
super(name, color: color);
}
class Label {
final String _text;
final int _size;
Label({required String text, int size = 12}) : _text = text, _size = size;
@override
String toString() => '$_text@$_size';
}
dart analyze lists the issues:
info - lib\shapes.dart:6:7 - Use an initializing formal to assign a parameter to a field. Try using an initialing formal ('this.name') to initialize the field. - prefer_initializing_formals
info - lib\shapes.dart:7:7 - Use an initializing formal to assign a parameter to a field. Try using an initialing formal ('this.color') to initialize the field. - prefer_initializing_formals
info - lib\shapes.dart:13:3 - Parameters ''name' and 'color'' could be super parameters. Trying converting ''name' and 'color'' to super parameters. - use_super_parameters
info - lib\shapes.dart:14:7 - Use an initializing formal to assign a parameter to a field. Try using an initialing formal ('this.radius') to initialize the field. - prefer_initializing_formals
info - lib\shapes.dart:22:50 - Use an initializing formal to assign a parameter to a field. Try using an initialing formal ('this._text') to initialize the field. - prefer_initializing_formals
info - lib\shapes.dart:22:64 - Use an initializing formal to assign a parameter to a field. Try using an initialing formal ('this._size') to initialize the field. - prefer_initializing_formals
dart fix --apply fixes all of them:
lib\shapes.dart
prefer_initializing_formals - 5 fixes
use_super_parameters - 1 fix
6 fixes made in 1 file.
Result:
class Shape {
final String name;
final String color;
Shape(this.name, {this.color = 'black'});
}
class Circle extends Shape {
final double radius;
Circle(super.name, this.radius, {super.color});
}
class Label {
final String _text;
final int _size;
Label({required this._text, this._size = 12});
@override
String toString() => '$_text@$_size';
}
The fix dropped = 'black' from Circle's color, because the super parameter inherits that default from Shape. Callers don't change: Label(text: 'Hi') still works. To apply one kind of fix at a time, use dart fix --apply --code=use_super_parameters. To go further and move the fields into the class header, see the use_primary_constructors lint in Primary constructors.
When not to use the shorthands
- The value needs transforming.
this.xandsuper.xpass the argument through unchanged. To trim, validate-and-convert or compute, take a plain parameter and use the initializer list:: email = raw.trim().toLowerCase()or: super(name.toUpperCase()). Anassertin the initializer list can still check athis.xvalue. - The public name would be misleading.
{this._x}exposes the parameter asx. If the field is_rawJsonbut callers should passjson:, use a plain parameter namedjson. - Factory and redirecting constructors. They can't use
this.x; they take plain parameters.
Summary
this.xsets fieldxfrom the argument, with the field's type. It works with positional, optional and named parameters,requiredand defaults. It is a final local in the initializer list. Not allowed in factory or redirecting constructors.super.x(Dart 2.17) forwards an argument to the superclass constructor, inheriting its type and default value but notrequired. Named super parameters match by name, positional ones by position. Don't mix positional super parameters with positional arguments insuper(...).{this._x}(Dart 3.12) sets a private field from a named argument that callers write asx:. The public name must be a valid identifier and unique, and subclasses forward it assuper.x.- Enable
prefer_initializing_formals,use_super_parameters,matching_super_parametersandtype_init_formals, then rundart fix --applyto convert old constructors.