npx skills add ...
npx skills add flutter/agent-plugins --skill dart-use-primary-constructors
npx skills add flutter/agent-plugins --skill dart-use-primary-constructors
Help users write syntactically and semantically correct primary constructors in Dart, and migrate/use the new constructor syntax, empty-body semicolon syntax, in-body initializer list syntax, and abbreviated concise constructor syntax.
The same skill content is published under more than one repo. The install counts are split across them; any of these commands works.
Use this skill when helping users write, refactor, or debug code using Dart's Primary Constructors feature.
primary-constructors via --enable-experiment=primary-constructors or in analysis_options.yaml:Primary Constructors allow developers to declare a non-redirecting generative constructor as well as a set of instance variables directly in the class header. This significantly reduces boilerplate and improves code readability.
;).To declare a primary constructor, place a parameter list immediately after the type name (and optional type parameters):
A primary constructor parameter list distinguishes between three types of parameters:
var or final modifier (e.g., final int x). They implicitly create a corresponding instance field in the class.this. or super. prefix (e.g., this.x or super.x). They initialize an existing field or a super constructor parameter, respectively.int y). They do not become fields and are only available during initialization (e.g., in field initializers or the this : initializer list in the class body).Declaring parameters and initializing parameters are two ways of achieving the same goal: declaring a class with instance fields which are set in the constructor. Regular parameters are different in that their values are not automatically routed to an instance field.
To make a primary constructor const, place the const keyword before the class/type name in the declaration header:
Extension types must use primary constructors.
var modifier (using var triggers the representation_field_modifier error).final modifier. If final is not present then it is inferred; that is, the parameter is declaring whether or not it's explicitly final.;)When a class, mixin class, mixin, extension or extension type has an empty body, the {} braces can be replaced by a semicolon (;):
this ...)If a primary constructor requires assertions or custom field initializations, they can be declared in the body using the this : syntax:
You can also write a constructor body with this syntax (this {...}).
For constructors declared within the class body, the class name can be omitted and replaced with the new or factory keywords:
| Traditional Syntax | Abbreviated Concise Syntax |
|---|---|
MyClass() {} | new() {} |
MyClass.name() {} | new name() {} |
const MyClass(); | const new(); |
const MyClass.name(); | const new name(); |
factory MyClass() => ... | factory() => ... |
factory MyClass.name() => ... | factory name() => ... |
When a primary constructor is declared, its formal parameters are introduced into the Primary Initializer Scope. This scope is the current scope for non-late field initializers in the class body and the primary constructor's initializer list (after this :).
This allows non-late fields to reference constructor parameters directly during declaration:
The primary initializer scope is not active for late instance variable initializers.
late variables can be evaluated after construction has completed, their initializers cannot safely access constructor parameters.late field initializer results in a compile-time error.Primary constructor parameters shadow class members (fields) of the same name within the primary initializer scope:
int y = x refers to parameter x.late initializer: late int y = x refers to field x (if it exists) because the parameter x is out of scope.To guarantee that the primary constructor (and the associated initializer scope) always executes:
Primary constructor parameters are non-assignable inside the initialization phase.
p = value, p++) inside field initializers or the this : initializer list is a compile-time error.Initializing a field twice (e.g., once in the field declaration/initializer and once in the this : initializer list or as an initializing formal) is a compile-time error.
Most errors and lints have quick-fixes, run dart fix to fix those violations. For other common errors, fix them using the following table:
| Error / Lint Code | Common Cause | Resolution |
|---|---|---|
| Invalid Late Access | Referencing a primary constructor parameter inside a late field initializer. | Make the field non-late, or pass the value through another non-late field. |
fieldInitializedInInitializerAndDeclaration | Initializing a variable both in its declaration and in the this : list. | Remove one of the initializations. |
nonRedirectingGenerativeConstructorWithPrimary | Declaring a in-body generative constructor in the body without redirecting to the primary. | Change the in-body constructor such that it is redirecting (e.g. this(...)) or remove the in-body constructor. |
Follow these steps to migrate a verbose class to the new primary constructor syntax:
Identify Candidate Fields and Constructor:
Locate generative constructors and the fields they initialize. In this case, this would be the name and age fields.
Move Fields to the Header:
Place fields in the header with final or var modifiers and append a semicolon (;) if the body is empty. The name and age fields are now written the primary constructor as declaring parameters final String name and final int age, respectively.
Handle Custom Initializers and Assertions:
If there is an initializer list or assert block, move it to a this block inside the body:
Leverage Primary Initializer Scope for Calculations: If a field value is calculated from parameters, declare it inside the body and assign it directly using the parameters:
Convert In-Body Constructors to Redirecting: Ensure all in-body generative constructors redirect to the primary constructor:
When the user prefers to keep the constructor in the class body but wants to reduce verbosity, suggest the abbreviated constructor syntax:
// `x` is a field and a parameter because it has the keyword `final`. In particular, we can use the name `x` in the initializer list in the in-body part of the primary constructor. 'y' is a only parameter because it has neither of the keywords `final` or `var`, but `y` is passed to the super constructor via the `this :` initializer list.
class C(final int x, int y) extends Base {
this : super(y);
}class const Point(final int x, final int y);
extension type const Ext(int x);
enum const MyEnum(final int x) {
entry(1);
}class C(int x);
mixin class MC;
extension type ET(int x);
mixin M;
extension Ext on C;class Point(var int x, var int y) {
// Initializer list in class body
this : assert(x >= 0), y = y * 2;
}