Skip to content
This repository was archived by the owner on Jul 16, 2023. It is now read-only.
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

* Don't trigger prefer-extracting-callbacks on empty function blocks.
* Improve unused files check, add support for `vm:entry-point` annotation.

## 4.3.1
Expand Down
4 changes: 3 additions & 1 deletion doc/rules/prefer-extracting-callbacks.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ prefer-extracting-callbacks

Warns about inline callbacks in a widget tree and suggests to extract them to widget methods in order to make a `build` method more readable. In addition extracting can help test those methods separately as well.

**NOTE** the rule will not trigger on arrow functions like `onPressed: () => _handler(...)` in order to cover cases when a callback needs a variable from the outside.
**NOTE** the rule will not trigger on:
Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

- arrow functions like `onPressed: () => _handler(...)` in order to cover cases when a callback needs a variable from the outside;
- empty blocks.

Use `ignored-named-arguments` configuration, if you want to ignore specific named parameters (`builder` argument is ignored by default).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,21 @@ class _InstanceCreationVisitor extends RecursiveAstVisitor<void> {

if (_isNotIgnored(argument) &&
expression is FunctionExpression &&
expression.body is BlockFunctionBody) {
_hasNotEmptyBlockBody(expression)) {
_expressions.add(argument);
}
}
}

bool _hasNotEmptyBlockBody(FunctionExpression expression) {
final body = expression.body;
if (body is! BlockFunctionBody) {
return false;
}

return body.block.statements.isNotEmpty;
}

bool _isNotIgnored(Expression argument) =>
argument is! NamedExpression ||
(argument.name.label.name != 'builder' &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,23 @@ class MyAnotherWidget extends StatelessWidget {
void _someMethod() {}
}

class MyWidgetWithEmptyCallbacks extends StatelessWidget {
@override
Widget build(BuildContext context) {
final widget = AnotherButton(
() {},
Container(),
);

return TextButton(
onPressed: () {
// Just a comment here.
},
child: Container(),
);
}
}

class Widget {}

class StatelessWidget extends Widget {}
Expand Down