writeMemoizedGetterWithBody function

void writeMemoizedGetterWithBody({
  1. required StringBuffer buffer,
  2. required String getterName,
  3. required String returnType,
  4. required String code,
  5. required GenerationOptions options,
  6. bool hasOverride = false,
})

Writes the following dart code into the buffer:

ReturnType _getterName;
ReturnType get getterName => _getterName ??= _constructGetterName();
ReturnType _constructGetterName() {
  code
}

This means that the generated code will also be responsible for writing the return statement and more.

When we're emitting nnbd-code, this method will write

late final ReturnType get getterName => _constructGetterName();
ReturnType _constructGetterName() {
  code
}

Implementation

void writeMemoizedGetterWithBody(
    {required StringBuffer buffer,
    required String getterName,
    required String returnType,
    required String code,
    required GenerationOptions options,
    bool hasOverride = false}) {
  final constructingMethod = '_construct${ReCase(getterName).pascalCase}';

  // We only need another field without nnbd
  if (!options.nnbd) buffer.write('$returnType _$getterName;\n');

  if (hasOverride) {
    buffer.write('@override\n');
  }
  if (options.nnbd) {
    buffer
        .writeln('late final $returnType $getterName = $constructingMethod();');
  } else {
    buffer
      ..write('$returnType get $getterName =>')
      ..writeln(' _$getterName ??= $constructingMethod();');
  }

  buffer
    ..write('$returnType $constructingMethod() {\n')
    ..write(code)
    ..writeln('\n}');
}