Skip to content

Const constructor initializer does not infer const for nested constructor invocation #4728

Description

@stan-at-work

Description

Inside a const constructor, a nested const constructor invocation passed
through a redirecting this(...) initializer is reported as:

Invalid constant value.

Adding an explicit const before the nested constructor invocation fixes the
error.

This is surprising because the surrounding constructor is declared const,
and the this(...) invocation must itself produce a constant object.

Minimal reproduction

class OrderViewPrintConfiguration {
  const OrderViewPrintConfiguration.initial();
}

class OrderViewConfiguration {
  final bool ignoreUndefinedFloorPlate;
  final OrderViewPrintConfiguration orderViewPrintConfiguration;

  const OrderViewConfiguration({
    required this.ignoreUndefinedFloorPlate,
    required this.orderViewPrintConfiguration,
  });

  const OrderViewConfiguration.initial()
      : this(
          ignoreUndefinedFloorPlate: false,
          orderViewPrintConfiguration:
              OrderViewPrintConfiguration.initial(),
        );
}

The analyzer reports:

Invalid constant value.

Workaround

Explicitly adding const fixes the error:

const OrderViewConfiguration.initial()
    : this(
        ignoreUndefinedFloorPlate: false,
        orderViewPrintConfiguration:
            const OrderViewPrintConfiguration.initial(),
      );

Expected behavior

One of the following would be preferable:

  1. Treat the arguments of the redirecting this(...) invocation in a const
    constructor as a const context, allowing the nested const keyword to be
    omitted.

  2. If the current behavior is intentional, produce a more specific diagnostic
    and quick-fix:

    This constructor invocation must be constant. Try adding const.

The current Invalid constant value diagnostic does not make it clear that
the nested constructor is const-capable and only requires an explicit keyword.

Actual behavior

The invocation is rejected unless const is written explicitly.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions