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
427 stars 66 forks source link

No way to create a FunctionType with a required named parameter #337

Closed srawlins closed 2 years ago

srawlins commented 3 years ago

I can create a FunctionType with a named parameter like so:

FunctionType((b) {
  b
      ..returnType = refer('int')
      ..requiredParameters.add(refer('String'))
      ..namedParameters['p1'] = refer('double');
}); // => int Function(String, {double p1});

But there is no way to make that named parameter required; no way to generate int Function(String, {required double p1}). I imagine this would require a breaking change. 😦

This is required for mockito. If a user has a class:

class C {
  void f(void Function({required int i}) p) {}
}

then it is impossible to generate a subclass of C with a legal overriding f.

smiLLe commented 2 years ago

Having the same issue. @srawlins Is there any workaround?

srawlins commented 2 years ago

Not that I know of.

smiLLe commented 2 years ago

@srawlins What is possible is to add 'required' into the refer():

FunctionType((b) {
  b
      ..returnType = refer('int')
      ..requiredParameters.add(refer('String'))
      ..namedParameters['p1'] = refer('required double');
}); 
srawlins commented 2 years ago

Ah that's a nice hack. That could definitely break at some point, but I like it for now.