dart-lang/code_builder

AssignFinal to nullable type doesn't generate the nullable type

Opened this issue · 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!

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.

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

still waiting for a fix

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