dart-lang / code_builder

A fluent API for generating valid Dart source code
https://pub.dev/packages/code_builder
BSD 3-Clause "New" or "Revised" License
423 stars 66 forks source link

Named Required Parameters are expected to be passed as optionalParameters #385

Open eseidel opened 1 year ago

eseidel commented 1 year ago

Named Required Parameters are expected to be passed as optionalParameters

I had initially written my code to pass required named parameters into the requiredParameters array, that appears to be wrong. It generates this:

// generates "fib(required int i)" // which is invalid dart.
      Method(
        (b) => b
          ..name = 'fib'
          ..requiredParameters.add(
            Parameter(
              (b) => b
                ..name = 'i'
                ..named = true
                ..required = true
                ..type = refer('int').type,
            ),
          ),
      );

There is even a test for this. 🤣 https://github.com/dart-lang/code_builder/blob/master/test/specs/method_test.dart#L496

The meta issue is that the split between "requiredParameters" and "optionalParameters" doesn't make sense (and isn't documented): https://pub.dev/documentation/code_builder/latest/code_builder/MethodBuilder-class.html (There is no mention of what type of Parameters should end up in one vs the other.)

eseidel commented 1 year ago

I suspect that before the addition of the "required" keyword to the language, all named arguments were functionally optional so I can see how we got here. :)

NAMEER242 commented 2 months ago

For anyone still want to create a required named arguments, you can use the optionalParametersfor both optinal and requeired parameters like this:

Parameter(
    (b) => b
     ..name = 'requiredParam'
     ..named = true
     ..required = true
     ..type = refer('int').type,
),

and for optinal use:

Parameter(
    (b) => b
     ..name = 'requiredParam'
     ..named = true
     ..type = refer('int').type,
),