code_builder icon indicating copy to clipboard operation
code_builder copied to clipboard

AssignFinal to nullable type doesn't generate the nullable type

Open johanflint opened this issue 4 years ago • 4 comments

When using code_builder I noticed that if I use assignFinal with a nullable type, it doesn't output the question mark.

Reproduction recipe:

final statement = refer('foo')
    .assignFinal(
        'bar',
        TypeReference((b) => b
          ..symbol = 'String'
          ..isNullable = true))
    .statement;
print(DartFormatter().format('${statement.accept(DartEmitter.scoped(useNullSafetySyntax: true))}'));

Output: final String bar = foo; Expected: final String? bar = foo;

Is this a bug or am I missing something obvious here? Thanks for the great package, it's a joy to use!

johanflint avatar Mar 28 '21 19:03 johanflint

Yeah I see a few issues with assignFinal, assignConst, and assignVar. They all use TypeReference.expression, which uses ScopedCode, which only references the symbol in its toString, not the type arguments, nor the nullability. So this:

void main() {
  final statement2 = refer('foo')
      .assignFinal(
          'bar',
          TypeReference((b) => b
            ..symbol = 'List'
            ..types.add(refer('int'))))
      .statement;
  print(DartFormatter().format(
      '${statement2.accept(DartEmitter.scoped())}'));
}

prints final List bar = foo;, omitting the <int> type argument.

srawlins avatar Mar 29 '21 17:03 srawlins

Ah indeed. I use ...symbol = 'List?' as a workaround, but it feels like cheating :).

johanflint avatar Mar 29 '21 18:03 johanflint

still waiting for a fix

Lohann avatar Feb 22 '23 22:02 Lohann

assignFinal and the related APIs are deprecated. It looks like this bug might exist in the replacements too

natebosch avatar Feb 23 '23 03:02 natebosch