isInstanceCreationExpressionOnlyUsingParameter function

bool isInstanceCreationExpressionOnlyUsingParameter(
  1. InstanceCreationExpression node, {
  2. required String parameter,
  3. Set<String> ignoredParameters = const {},
})

Checks whether an instance creation uses only the specified named parameter.

Returns true when the node has:

  • Only one relevant named argument whose name equals parameter
  • The argument value is not a null literal and the argument type is not nullable (i.e. not T?)
  • No other arguments are present, except those explicitly listed in ignoredParameters

Otherwise returns false.

Implementation

bool isInstanceCreationExpressionOnlyUsingParameter(
  InstanceCreationExpression node, {
  required String parameter,
  Set<String> ignoredParameters = const {},
}) {
  var hasParameter = false;

  for (final argument in node.argumentList.arguments) {
    if (argument case NamedExpression(
      name: Label(label: SimpleIdentifier(name: final argumentName)),
      :final expression,
      :final staticType,
    )) {
      if (ignoredParameters.contains(argumentName)) {
        continue;
      } else if (argumentName == parameter &&
          expression is! NullLiteral &&
          staticType?.nullabilitySuffix != NullabilitySuffix.question) {
        hasParameter = true;
      } else {
        // Other named arguments are not allowed
        return false;
      }
    } else {
      // Other arguments are not allowed
      return false;
    }
  }
  return hasParameter;
}