runWithReporter method
Override this method to implement your lint rule.
Use context to register callbacks for AST node types:
context.addMethodInvocation((node) {
if (condition) {
reporter.atNode(node);
}
});
Implementation
@override
void runWithReporter(
SaropaDiagnosticReporter reporter,
SaropaContext context,
) {
context.addMethodDeclaration((MethodDeclaration node) {
if (node.name.lexeme != 'build') return;
final FunctionBody body = node.body;
// Collect all return statements in the build method
final List<ReturnStatement> returns = <ReturnStatement>[];
_collectReturnStatementsForElement(body, returns);
if (returns.length < 2) return;
// Check if returns are in different branches of conditionals
final Set<String> returnTypes = <String>{};
for (final ReturnStatement ret in returns) {
final Expression? expr = ret.expression;
if (expr is InstanceCreationExpression) {
returnTypes.add(expr.constructorName.type.name.lexeme);
} else if (expr is MethodInvocation) {
returnTypes.add(expr.methodName.name);
}
}
// If different widget types are returned, warn
if (returnTypes.length > 1) {
reporter.atNode(node);
}
});
}