code_builder
code_builder copied to clipboard
TypeReference for a class shouldn't add a ? when calling constructor or class property.
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:
- See our contributor guide for general expectations for PRs.
- Larger or significant changes should be discussed in an issue before creating a PR.
- Contributions to our repos should follow the Dart style guide and use
dart format. - Most changes should add an entry to the changelog and may need to rev the pubspec package version.
- Changes to packages require corresponding tests.
Note that many Dart repos have a weekly cadence for reviewing PRs - please allow for some latency before initial review feedback.
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.
Closing as the dart-lang/code_builder repository is merged into the dart-lang/tools monorepo. Please re-open this PR there!