code_builder icon indicating copy to clipboard operation
code_builder copied to clipboard

TypeReference for a class shouldn't add a ? when calling constructor or class property.

Open PhiFry opened this issue 1 year ago • 1 comments

When building code for TypeReference.newInstance/Named and the type had isNullable = true the resulting code becomes Foo?.namedConstructor() which for my use case was not what I wanted.

Here is my use case:

// useNullSafetySyntax = true

final class PluginField extends BaseField {
  PluginField.fromJson(Map<String, dynamic> data, String name)
      : isRequired = data["required"],
        super.fromJson(data, name);
  final bool isRequired;

  @override
  late final TypeReference type = TypeReference((t) {
    t.symbol = "$Plugin";
    t.isNullable = !isRequired;
  });

  @override
  Expression buildInitializer(CodeExpression valueExpression) {
    final expression = type.newInstanceNamed("fromJson", [valueExpression]);
    if (isRequired) return expression;
    return valueExpression.isNotA(refer("$Map")).conditional(literalNull, expression);
  }
}

class Plugin {
  Plugin.fromJson(Map<String, dynamic> data) : name = data["name"];
  final String name;
}

type in this case is shared between a caller building a declaration off of it and buildInitializer building initializer code in a constructor.

The resulting code before this PR for buildInitializer was Plugin?.fromJson(data["value"]) when isRequired = false (isNullable = true).

I think it makes sense to have a TypeReference not add a ? onto the type when calling a constructor or static property but to add it when being used to declare a property.


  • [x] I’ve reviewed the contributor guide and applied the relevant portions to this PR.
Contribution guidelines:

Note that many Dart repos have a weekly cadence for reviewing PRs - please allow for some latency before initial review feedback.

PhiFry avatar May 08 '24 17:05 PhiFry

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

google-cla[bot] avatar May 08 '24 17:05 google-cla[bot]

Closing as the dart-lang/code_builder repository is merged into the dart-lang/tools monorepo. Please re-open this PR there!

mosuem avatar Oct 29 '24 15:10 mosuem