目录

prefer_const_constructors

目录

Prefer const with constant constructors.

This rule is available as of Dart 2.0.

This rule has a quick fix available.

Details

#

PREFER using const for instantiating constant constructors.

If a constructor can be invoked as const to produce a canonicalized instance, it's preferable to do so.

BAD:

dart
class A {
  const A();
}

void accessA() {
  A a = new A();
}

GOOD:

dart
class A {
  const A();
}

void accessA() {
  A a = const A();
}

GOOD:

dart
class A {
  final int x;

  const A(this.x);
}

A foo(int x) => new A(x);

Usage

#

To enable the prefer_const_constructors rule, add prefer_const_constructors under linter > rules in your analysis_options.yaml file:

analysis_options.yaml
yaml
linter:
  rules:
    - prefer_const_constructors