DartAdvanced 2 min read

Dart primary constructors: concise immutable models

Declare simple model fields in a class header while preserving clear validation boundaries.

On this page

A small model can spend more lines assigning fields than describing its purpose. Primary constructors reduce that repetition. They are useful for straightforward data holders, while complex validation can still deserve a named factory or an explicit body.

Worked example

Language requirement: Dart 3.13 or later. This complete example uses browser-supported libraries.

main.dart
// @dart = 3.13
class InvoiceLine(final String sku, final int quantity, final int unitPricePaise) {
  int get totalPaise => quantity * unitPricePaise;
}

void main() {
  final line = InvoiceLine('CABLE-1', 2, 15000);
  print('${line.sku}: ${line.totalPaise} paise');
}

Follow the data and control flow

The final declaring parameters induce instance fields in the class header. The getter calculates a value from those fields, and the instance behaves like a model built with an equivalent traditional constructor. A primary-constructor parameter without a declaring modifier does not automatically become a field.

Dart 3.13 also supports concise constructor syntax inside the class body. Learn that as a separate writing option, not as a different object lifecycle. Keep argument names readable when several parameters have the same type; concise syntax should not make call sites ambiguous.

The source directive selects this library’s language version so a browser editor’s older default package constraint does not disable primary constructors. It requires a compiler that supports Dart 3.13; it does not upgrade an older SDK.

A mistake to avoid

The shorter declaration does not validate a negative quantity or price. Add an explicit construction boundary for untrusted values. Do not insert final on ordinary function parameters in newer language versions; declaring parameters in this constructor context have a different role.

Practice and verification

Rewrite the model using a traditional constructor and compare behavior. Then add a validated factory and decide which constructor should remain public. Verify the package’s minimum language version before copying this into an older project.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.