Dart: Is there a disadvantage to using const constructor?

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.

  2. 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:

    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.)

  3. 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.

  4. 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.

Leave a Comment