Dart: Is there a disadvantage to using const constructor?

Issue

There is an analyzer/lint check to warn me when it is possible to use a const constructor: https://dart-lang.github.io/linter/lints/prefer_const_constructors.html

(ie. using final a = const A(); instead of final a = A();)

I think to understand the advantages (there will only ever be one instance with the same constant values for a const constructor). But why isn’t this the default? Since dart 2 the new can be omitted, so why didn’t they change the definition of creating a new instance which can be created const simply as const instead of new? I assume there must be some disadvantage to having everything const?

(for example in a constant context like const [A()] it is actually the same as const [const A()], so why not everywhere)?

Solution

so why didn’t they change the definition of creating a new instance which can be created const simply as const instead of new?

If you mean why doesn’t final a = A(); automatically assume const A() if A has a const constructor:

  1. Sometimes it is automatic:
    const a = A();
    

in which case A‘s constructor is being invoked in a const context and doesn’t need an extra const qualifier on the right-hand-side.

  1. An explicit const expresses intent. For example, suppose you had:
    final a = A(B());
    

where A and B have const constructors. Later, somebody makes a change:

```dart
final a = A(C());
```

where C does not have a const constructor. If const were automatic, then you would have no idea that a is no longer const. Maybe that’s okay, but it also could suddenly have a negative impact on your application’s performance, and without an explicit const qualifier, the impact of a local change could have a much wider scope than expected. (That said, explicit const qualifiers and automatically adding them aren’t mutually exclusive.)

  1. const can have downsides. const creates compile-time constants. If you have:

    final a1 = A();
    final a2 = A();
    

identical(a1, a2) is not true. If const A() were implicit, then identical(a1, a2) would be true, and maybe that’s not a property that the code intended to have.

  1. Compile-time constants live forever. The whole point is to have an object that can be reused instead of re-constructing it. The flipside is that won’t be destroyed.

Answered By – jamesdlin

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *