Dot shorthands
suggest changeDart 3.10 added dot shorthands: when the compiler already knows which type an expression must have, you can leave out the type name and write only .member. Color.red becomes .red, Duration.zero becomes .zero, and Point.origin() becomes .origin().
This article covers:
- enum values, static members and constructors (
.new, named, factory,const) - where the context type comes from, and nullable and
Futurecontexts - shorthands in
switchcases, patterns and==comparisons - chaining members after a shorthand
- the places where shorthands don't work, with the analyzer errors you get
- a larger example, plus advice on when a shorthand helps readability and when it hurts
All examples were run with Dart 3.13.4. They need a language version of 3.10 or later, so set sdk: ^3.10.0 (or higher) in pubspec.yaml.
A first example
Named arguments that take an enum are where dot shorthands help most:
enum LogLevel { debug, info, warning, error }
void log(String message, {LogLevel level = .info}) {
print('[${level.name}] $message');
}
void main() {
// Before Dart 3.10 you had to repeat the type name.
log('starting', level: LogLevel.debug);
// With dot shorthands the parameter type supplies it.
log('starting', level: .debug);
log('disk almost full', level: .warning);
log('ready');
}
Output:
[debug] starting
[debug] starting
[warning] disk almost full
[info] ready
level: .debug means exactly the same as level: LogLevel.debug. The parameter's type is LogLevel, so .debug is looked up among the static members of LogLevel. The default value = .info works the same way.
Dot shorthands are only syntax. The code compiles to the same thing as the long form, with no runtime cost. The type is still checked statically: a misspelled .debgu is a compile error, not a runtime failure.
Enum values
Enums are the most common use. Shorthands work in variable declarations, switch cases, switch expressions, == comparisons, collection literals and arguments:
enum Suit { clubs, diamonds, hearts, spades }
String color(Suit s) => switch (s) {
.hearts || .diamonds => 'red',
.clubs || .spades => 'black',
};
void main() {
Suit s = .hearts;
print(color(s));
switch (s) {
case .spades:
print('trump');
case .clubs || .diamonds || .hearts:
print('not trump');
}
if (s == .hearts) print('a heart');
if (s != .spades) print('not a spade');
final hand = <Suit>[.spades, .hearts, .hearts];
print(hand);
print(hand.indexOf(.hearts));
Suit parsed = .values.byName('clubs');
print(parsed);
}
Output:
red
not trump
a heart
not a spade
[Suit.spades, Suit.hearts, Suit.hearts]
1
Suit.clubs
Some things to note:
- Exhaustiveness checking is unchanged. If you remove
.spadesfrom theswitchexpression, the compiler reports that the switch isn't exhaustive, just as withSuit.spades. .valuesis a static member of every enum, so.values.byName('clubs')works when the context type isSuit.hand.indexOf(.hearts)works because the parameter ofList<Suit>.indexOfhas typeSuit. As shown below,containsdoesn't work, because its parameter has typeObject?.
For enum basics see Basic usage, and for switch see Switch Case.
Static fields, getters and methods
A shorthand can name any static member of the context type: a field, a getter or a method. It's not limited to enums:
class Temperature {
final double celsius;
const Temperature(this.celsius);
static const freezing = Temperature(0);
static const boiling = Temperature(100);
static Temperature fromFahrenheit(double f) => Temperature((f - 32) * 5 / 9);
static Temperature? tryParse(String s) {
if (s.endsWith('C')) {
final v = double.tryParse(s.substring(0, s.length - 1));
return v == null ? null : Temperature(v);
}
return null;
}
@override
String toString() => '${celsius.toStringAsFixed(1)}°C';
}
void report(Temperature t) => print('reading: $t');
void main() {
report(.freezing);
report(.fromFahrenheit(98.6));
Temperature? maybe = .tryParse('21.5C');
print(maybe);
Temperature? bad = .tryParse('hot');
print(bad);
// Static members of core library types work the same way.
int n = .parse('42');
double limit = .infinity;
Duration timeout = .zero;
BigInt big = .two.pow(100);
Uri uri = .parse('https://dart.dev/language');
DateTime release = .utc(2025, 11, 12);
print([n, limit, timeout, big, uri.host, release.year]);
}
Output:
reading: 0.0°C
reading: 37.0°C
21.5°C
null
[42, Infinity, 0:00:00.000000, 1267650600228229401496703205376, dart.dev, 2025]
.tryParse returns Temperature?, and the variable has type Temperature?. For a nullable context type T?, the shorthand is looked up in T. The result only has to be assignable to the context type.
The core library has many static members that read well as shorthands: int.parse, double.infinity, Duration.zero, BigInt.two, Uri.parse, DateTime.utc. See Static members for more on static members.
Constructors: .new, named, factory and const
A shorthand can also call a constructor. The unnamed constructor is written .new(...), and named and factory constructors use their name:
class Point {
final int x, y;
const Point(this.x, this.y);
const Point.origin() : this(0, 0);
factory Point.parse(String s) {
final [a, b] = s.split(',');
return Point(int.parse(a), int.parse(b));
}
@override
String toString() => '($x, $y)';
}
class Rect {
final Point topLeft;
final Point bottomRight;
const Rect(this.topLeft, this.bottomRight);
@override
String toString() => 'Rect$topLeft-$bottomRight';
}
void main() {
Point a = .new(3, 4); // unnamed constructor
Point b = .origin(); // named constructor
Point c = .parse('7,8'); // factory constructor
print([a, b, c]);
const Point d = .origin(); // const context: constructor must be const
final r = Rect(.origin(), .new(10, 5));
const r2 = Rect(.origin(), .new(1, 1));
print([d, r, r2]);
// Explicit const inside a non-const context.
Point e = const .new(1, 2);
print(identical(e, const Point(1, 2)));
// Type arguments are inferred from the context type.
List<int> zeros = .filled(3, 0);
Map<String, int> ages = .fromIterables(['ann', 'bob'], [31, 27]);
Iterable<String> none = .empty();
print([zeros, ages, none]);
}
Output:
[(3, 4), (0, 0), (7, 8)]
[(0, 0), Rect(0, 0)-(10, 5), Rect(0, 0)-(1, 1)]
true
[[0, 0, 0], {ann: 31, bob: 27}, ()]
.new(3, 4)calls the unnamed constructorPoint(3, 4). You can't write.(3, 4)or.Point(3, 4).- In a const context, for example
const Point d = .origin();or the arguments ofconst Rect(...), the shorthand is const too. The constructor must therefore be aconstconstructor. const .new(1, 2)creates a constant where the context isn't const.- Generic type arguments are inferred from the context type.
List<int> zeros = .filled(3, 0)callsList<int>.filled(3, 0).
For more on constructors see Constructors and Creating a class.
Where the context type comes from
The context type is the type the surrounding code expects for an expression. It is the same type Dart uses to infer [] as List<int> in List<int> xs = [];. The shorthand is looked up in that type. A context type comes from:
import 'dart:async';
enum Status { active, suspended, closed }
class Account {
Status status;
Account({this.status = .active}); // default value
}
Status parse(String s) => .values.byName(s); // return value
Future<Status> fetch() async => .suspended; // Future<T> return: context is T
FutureOr<Status> cached() => .closed; // FutureOr<T> too
Status? overrideFor(String user) => user == 'bob' ? .suspended : null;
Status initialStatus({required bool verified}) =>
verified ? .active : .suspended; // both branches of ?:
T first<T>(List<T> items, T fallback) => items.isEmpty ? fallback : items[0];
void main() async {
final acc = Account();
acc.status = .closed; // assignment
print(acc.status);
Status? manual = .suspended; // nullable context: T? looks in T
print(manual);
Status effective = overrideFor('ann') ?? .active; // right side of ??
print(effective);
print(initialStatus(verified: false));
print(parse('closed'));
print(await fetch());
print(await cached());
// Generic inference: T is solved from the context type.
Status picked = first([], .active);
print(picked);
// Collection elements with an explicit element type.
final byUser = <String, Status>{'ann': .active, 'bob': .closed};
print(byUser);
}
Output:
Status.closed
Status.suspended
Status.active
Status.suspended
Status.closed
Status.suspended
Status.closed
Status.active
{ann: Status.active, bob: Status.closed}
In summary, a shorthand works in these places:
| Place | Example | Looked up in |
|---|---|---|
| typed variable declaration | Status s = .active; |
Status |
| assignment | acc.status = .closed; |
type of the field or variable |
| argument | report(.freezing) |
parameter type |
| default value | {this.status = .active} |
parameter type |
return / => body |
Status parse(...) => .values.byName(s); |
return type |
async function returning Future<T> or FutureOr<T> |
Future<Status> f() async => .suspended; |
T |
right side of ?? |
x ?? .active |
context of the whole expression |
branches of ?: |
ok ? .active : .suspended |
context of the whole expression |
| elements of a typed collection literal | <String, Status>{'ann': .active} |
element or value type |
right side of == and != |
s == .hearts |
static type of the left side |
constant patterns in switch, if-case |
case .red: |
type of the matched value or field |
If the context type is nullable (Status?), the lookup happens in Status. If it is FutureOr<Status> (including the body of an async function returning Future<Status>), the lookup also happens in Status.
Equality and patterns
For == and !=, the right operand gets the static type of the left operand as its context. Patterns work in a similar way: a constant pattern gets its context from the value it's matched against. That includes fields in object patterns and positions in record patterns:
enum Light { red, yellow, green }
enum Mode { manual, automatic }
class Crossing {
final Light cars;
final Light walkers;
final Mode mode;
const Crossing(this.cars, this.walkers, {this.mode = .automatic});
}
String check(Crossing c) => switch (c) {
// Constant patterns inside object patterns: the field type is the context.
Crossing(mode: .manual) => 'officer in charge',
Crossing(cars: .green, walkers: .green) => 'DANGER',
Crossing(cars: .red, walkers: .green) => 'walk',
Crossing(walkers: != .green) => 'wait',
_ => 'unknown',
};
String pair((Light, Light) lights) => switch (lights) {
// Inside record patterns, each field's type is the context.
(.red, .red) => 'all stop',
(.green, _) || (_, .green) => 'someone moves',
_ => 'transition',
};
void main() {
print(check(Crossing(.green, .green)));
print(check(Crossing(.red, .green)));
print(check(Crossing(.yellow, .red)));
print(check(Crossing(.red, .red, mode: .manual)));
print(pair((.red, .red)));
print(pair((.yellow, .green)));
final Light now = .yellow;
if (now case .yellow || .red) print('cars stop soon');
if (now case == .yellow) print('relational pattern');
Light? sensor; // null until the first reading
print(sensor == .red); // left side is Light?, so .red is found in Light
}
Output:
DANGER
walk
wait
officer in charge
all stop
someone moves
cars stop soon
relational pattern
false
Crossing(mode: .manual)works becausemodehas typeMode, and(.red, .red)works because each position of the record has typeLight.- The relational pattern
!= .greengets its context from the matched value too. sensor == .redworks even thoughsensorisLight?. The?is removed before the lookup.
Only constant patterns can be shorthands. A type test such as Circle(:final r) still needs the class name. See Pattern matching and Destructuring for patterns in general.
Chaining after a shorthand
A shorthand can be followed by more member accesses, method calls, index operators or !. Only the first name is looked up in the context type. The rest of the chain is ordinary Dart, and the final result must be assignable to the context type:
enum Level { low, medium, high }
class Money {
final int cents;
const Money(this.cents);
Money times(int n) => Money(cents * n);
@override
String toString() => '\$${(cents / 100).toStringAsFixed(2)}';
}
void main() {
// The shorthand head is looked up in the context type;
// the rest of the chain is ordinary member access.
int n = .parse('-17').abs();
Level top = .values.last;
String s = .fromCharCodes([100, 97, 114, 116]).toUpperCase();
print([n, top, s]);
Money price = .new(1999).times(3);
print(price);
// A ! after the shorthand is part of the chain too.
int port = .tryParse('8443')!;
print(port);
}
Output:
[17, Level.high, DART]
$59.97
8443
.values.last first finds the static values getter on Level, then calls last on the resulting List<Level>. .tryParse('8443')! finds int.tryParse, which returns int?, and ! makes it an int.
Long chains get hard to read quickly. One extra call is usually fine, but more than that is clearer with the type name written out.
Where dot shorthands don't work
A shorthand needs a context type that has a matching static member. Here are the most common mistakes in one file:
enum Color { red, green, blue }
extension ColorDefaults on Color {
static Color get brand => Color.blue;
}
class Animal {
static Animal create() => Animal();
}
class Dog extends Animal {}
void main() {
var a = .red; // 1. no context type
Color c = .red;
if (.red == c) {} // 2. left operand of == has no context
print(.green); // 3. print takes Object?
final colors = [Color.red, .green]; // 4. no element type yet
List<Color> list = [.red];
list.contains(.red); // 5. contains takes Object?
Duration d = .zero + Duration(seconds: 1); // 6. operand of +
Color b = .brand; // 7. static extension members aren't found
Dog dog = .create(); // 8. static members aren't inherited
String s = .toString(); // 9. instance members can't be used
Animal Function() f = .new; // 10. no constructor tear-offs
}
dart analyze reports:
error - h.dart:14:11 - A dot shorthand can't be used where there is no context type. - dot_shorthand_missing_context
error - h.dart:16:7 - A dot shorthand can't be used where there is no context type. - dot_shorthand_missing_context
error - h.dart:17:10 - The static getter 'green' isn't defined for the context type 'Object'. Try correcting the name to the name of an existing static getter, or defining a getter or field named 'green'. - dot_shorthand_undefined_member
error - h.dart:18:30 - A dot shorthand can't be used where there is no context type. - dot_shorthand_missing_context
error - h.dart:20:18 - The static getter 'red' isn't defined for the context type 'Object'. Try correcting the name to the name of an existing static getter, or defining a getter or field named 'red'. - dot_shorthand_undefined_member
error - h.dart:21:16 - A dot shorthand can't be used where there is no context type. - dot_shorthand_missing_context
error - h.dart:22:14 - The static getter 'brand' isn't defined for the context type 'Color'. Try correcting the name to the name of an existing static getter, or defining a getter or field named 'brand'. - dot_shorthand_undefined_member
error - h.dart:23:14 - The static method or constructor 'create' isn't defined for the context type 'Dog'. Try correcting the name to the name of an existing static method or constructor, or defining a static method or constructor named 'create'. - dot_shorthand_undefined_member
error - h.dart:24:15 - The static method or constructor 'toString' isn't defined for the context type 'String'. Try correcting the name to the name of an existing static method or constructor, or defining a static method or constructor named 'toString'. - dot_shorthand_undefined_member
error - h.dart:25:25 - A dot shorthand can't be used where there is no context type. - dot_shorthand_missing_context
What each error means and how to fix it:
varandfinalwithout a type give no context. WriteColor a = .red;orvar a = Color.red;.- The left operand of
==has no context. Only the right side gets one, so writec == .red. print(.green): the parameter has typeObject?, so the lookup happens inObject, which has nogreen. The same goes forMap.containsKey,List.contains,List.remove, string interpolation and any parameter typedObject,Object?ordynamic.- Untyped collection literals: in
[Color.red, .green]the element type isn't known yet, because it is inferred from the elements themselves. Write<Color>[.red, .green]or give the variable a type. containstakesObject?. Use the full name:list.contains(Color.red).- Operands of arithmetic operators have no context.
.zero + Duration(seconds: 1)doesn't compile. UseDuration.zero + .... - Static members in extensions aren't found. Shorthands look only at the context type itself.
- Static members aren't inherited:
Dogdoesn't havecreateeven thoughAnimaldoes. The Static members article explains why. The context type must be the class that declares the member. - Instance members can't be used. A shorthand always names a static member or a constructor, never a method like
toString. - Tear-offs need an interface context type. A function type such as
Animal Function()isn't a class, so there is nothing to look.newup in. WriteAnimal.new.
If you use a shorthand in a package whose SDK constraint is below 3.10, or in a file with an older // @dart= comment, you get:
error - v.dart:5:13 - This requires the 'dot-shorthands' language feature to be enabled. Try updating your pubspec.yaml to set the minimum SDK constraint to 3.10.0 or higher, and running 'pub get'. - experiment_not_enabled
A larger example: configuring a table renderer
Dot shorthands are most useful in APIs with many enum and configuration arguments. Here a small text table renderer takes column definitions, alignment and an optional border:
enum Align { left, right, center }
sealed class Border {
const Border();
static const none = NoBorder();
const factory Border.line(String char) = LineBorder;
static const ascii = Border.line('-');
}
final class NoBorder extends Border {
const NoBorder();
}
final class LineBorder extends Border {
final String char;
const LineBorder(this.char);
}
class Column {
final String title;
final Align align;
final int width;
const Column(this.title, {this.align = .left, this.width = 10});
const Column.number(this.title) : align = .right, width = 8;
}
String pad(String s, int width, Align align) => switch (align) {
.left => s.padRight(width),
.right => s.padLeft(width),
.center => s.padLeft((width + s.length) ~/ 2).padRight(width),
};
String render(
List<Column> columns,
List<List<Object>> rows, {
Border border = .none,
}) {
final out = StringBuffer();
String line(List<Object> cells) => [
for (final (i, col) in columns.indexed)
pad('${cells[i]}', col.width, col.align),
].join(' | ');
final header = line([for (final c in columns) c.title]);
out.writeln(header);
if (border case LineBorder(:final char)) {
out.writeln(char * header.length);
}
for (final row in rows) {
out.writeln(line(row));
}
return out.toString();
}
void main() {
const columns = <Column>[
.new('Language', width: 12),
.new('Paradigm', align: .center, width: 14),
.number('Year'),
];
final rows = [
['Dart', 'multi', 2011],
['Smalltalk', 'object', 1972],
['Haskell', 'functional', 1990],
];
print(render(columns, rows, border: .ascii));
}
Output:
Language | Paradigm | Year
----------------------------------------
Dart | multi | 2011
Smalltalk | object | 1972
Haskell | functional | 1990
Some things to note:
<Column>[.new(...), .number(...)]builds the list with shorthand constructor calls, because the element type is written out. Without<Column>(or another declared type) this wouldn't compile.align: .centerand the defaults= .left/= .noneread like configuration rather than code..asciiis a static constant on the sealed classBorder, andBorder.lineis a factory that returns aLineBorder. A shorthand can return a subtype of the context type.- The
if (border case LineBorder(:final char))check still namesLineBorder, because type patterns can't be shorthands.
This style suits Flutter widget trees well. Flutter 3.38 ships with Dart 3.10, so Flutter code can use shorthands for alignment enums and similar arguments. This snippet wasn't run here because Flutter isn't installed:
Column(
mainAxisAlignment: .center,
crossAxisAlignment: .start,
children: [Text('Hello'), Text('World')],
)
mainAxisAlignment: .center means MainAxisAlignment.center, because that is the parameter's type.
Tooling
- IDEs that use the Dart analysis server (VS Code, IntelliJ, Android Studio) have a Convert to dot shorthand assist. Put the cursor on
Color.redand open the quick-fix menu. Code completion after a.suggests the members of the context type. - There is no lint rule that requires or forbids shorthands, and
dart fixdoesn't convert code. Older code keeps working unchanged:Color.redand.redare both valid. dart formatleaves shorthands as written.
When to use dot shorthands
Shorthands work best when the type is obvious from nearby code:
- Enum arguments and enum
switchcases:level: .warning,case .spades:. The parameter or switch subject makes the type clear, and the type name adds nothing. - Defaults and configuration:
{this.mode = .automatic},padding: .all(8). - Comparisons:
if (status == .closed)reads better than repeatingStatus. - Constructors on long generic types:
Map<String, List<int>> index = .new();instead of repeating the type arguments.
Write the type name when it adds information:
- When the member name is vague on its own.
timeout: .zerois clear, butfinal x = compute(.parse(input))makes the reader look up the parameter type to know what is being parsed. - Long chains after the shorthand, as described above.
- Unrelated types with the same member names.
.none,.emptyor.defaultValuecan belong to any of several classes, and the shorthand hides which one. - Public API examples and docs, where readers may not know the parameter types.
A good rule: use a shorthand when the meaning is clear without knowing the type, or when the type is visible within a line or two.
Summary
.nameis looked up as a static member or constructor of the context type, the type the surrounding code expects.- It works for enum values, static fields, getters and methods, and constructors (
.new(...),.named(...), factories,const). - Nullable
T?andFutureOr<T>/asyncreturn contexts look inT. - In
==and!=only the right side can be a shorthand. Constant patterns inswitchandif-casecan always be shorthands, including inside object and record patterns. - There's no context in
vardeclarations, untyped collection literals, operator operands, or parameters of typeObject?. Extension statics, inherited statics and instance members aren't found. - Requires language version 3.10 or later.