compute method
Computes the changes for this producer using builder.
This method should not modify fixKind.
Implementation
@override
Future<void> compute(ChangeBuilder builder) async {
final ClassDeclaration? classDecl = node
.thisOrAncestorOfType<ClassDeclaration>();
if (classDecl == null) return;
final ClassElement? classEl = classDecl.declaredFragment?.element;
if (classEl == null) return;
// если dispose уже есть — не предлагаем
final bool hasDispose = classDecl.getMethod('dispose') != null;
if (hasDispose) return;
final List<String> fields = _fieldsNeedingDispose(
classEl,
classDecl,
).toList()..sort();
if (fields.isEmpty) return;
// куда вставлять: перед build(), иначе перед закрывающей скобкой класса
final MethodDeclaration? buildMethod = classDecl.getMethod('build');
final int insertOffset =
buildMethod?.offset ?? classDecl.classRightBracket.offset;
final StringBuffer buffer = StringBuffer()
..writeln()
..writeln(' @override')
..writeln(' void dispose() {');
for (final String f in fields) {
buffer.writeln(' $f.dispose();');
}
buffer
..writeln(' super.dispose();')
..writeln(' }')
..writeln();
await builder.addDartFileEdit(file, (DartFileEditBuilder edit) {
edit.addSimpleInsertion(insertOffset, buffer.toString());
try {
edit.format(classDecl.sourceRange);
} catch (_) {}
});
}