Skip to main content

prefer_const_constructors

Use 'const' with the constructor to improve performance.

Description

#

The analyzer produces this diagnostic when an invocation of a const constructor isn't either preceded by const or in a constant context.

Example

#

The following code produces this diagnostic because the invocation of the const constructor is neither prefixed by const nor in a constant context:

dart
class C {
  const C();
}

C c = C();

Common fixes

#

If the context can be made a constant context, then do so:

dart
class C {
  const C();
}

const C c = C();

If the context can't be made a constant context, then add const before the constructor invocation:

dart
class C {
  const C();
}

C c = const C();