Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,14 @@ Rewrite the variable evaluation into return statement instead.""",
return;
}

final blockBody = statement.parent;
if (blockBody == null) return;
final functionBody = statement.thisOrAncestorOfType<FunctionBody>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about cases like:

final a = 3;
if (b) {
  return a;
}

a is still unnecessary here. Let's also add a test case like that

if (functionBody == null) return;

final visitor = AvoidUnnecessaryReturnVariableVisitor(
returnVariableElement,
statement,
);
blockBody.visitChildren(visitor);
functionBody.visitChildren(visitor);

if (!visitor.hasBadStatementCount()) return;

Expand Down
12 changes: 12 additions & 0 deletions lint_test/avoid_unnecessary_return_variable_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,15 @@ class _TestClass {
final finalField = 1;
var varField = 1;
}

/// Test the avoid_unnecessary_return_variable.
/// Good: returning cached variable where return variable is
/// declared at the outer block, and returned inside an inner block.
Future<String?> testAvoidUnnecessaryReturnVariableNestedBlock() async {
final cached = 'cached';
if (cached.isNotEmpty) {
// Should NOT trigger the avoid_unnecessary_return_variable lint
return cached;
}
return null;
}
Loading