Skip to content
This repository was archived by the owner on Jul 16, 2023. It is now read-only.

feat: add avoid-shrink-wrap-in-lists #918

Merged
merged 2 commits into from
Jul 20, 2022
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 @@ -3,6 +3,7 @@
## Unreleased

* feat: add static code diagnostic [`avoid-duplicate-exports`](https://dartcodemetrics.dev/docs/rules/common/avoid-duplicate-exports).
* feat: add static code diagnostic [`avoid-shrink-wrap-in-lists`](https://dartcodemetrics.dev/docs/rules/flutter/avoid-shrink-wrap-in-lists).
* feat: add static code diagnostic [`avoid-top-level-members-in-tests`](https://dartcodemetrics.dev/docs/rules/common/avoid-top-level-members-in-tests).
* feat: add static code diagnostic [`prefer-enums-by-name`](https://dartcodemetrics.dev/docs/rules/common/prefer-enums-by-name).

Expand Down
2 changes: 2 additions & 0 deletions lib/src/analyzers/lint_analyzer/rules/rules_factory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import 'rules_list/avoid_non_ascii_symbols/avoid_non_ascii_symbols_rule.dart';
import 'rules_list/avoid_non_null_assertion/avoid_non_null_assertion_rule.dart';
import 'rules_list/avoid_preserve_whitespace_false/avoid_preserve_whitespace_false_rule.dart';
import 'rules_list/avoid_returning_widgets/avoid_returning_widgets_rule.dart';
import 'rules_list/avoid_shrink_wrap_in_lists/avoid_shrink_wrap_in_lists_rule.dart';
import 'rules_list/avoid_throw_in_catch_block/avoid_throw_in_catch_block_rule.dart';
import 'rules_list/avoid_top_level_members_in_tests/avoid_top_level_members_in_tests_rule.dart';
import 'rules_list/avoid_unnecessary_setstate/avoid_unnecessary_setstate_rule.dart';
Expand Down Expand Up @@ -76,6 +77,7 @@ final _implementedRules = <String, Rule Function(Map<String, Object>)>{
AvoidNonNullAssertionRule.ruleId: AvoidNonNullAssertionRule.new,
AvoidPreserveWhitespaceFalseRule.ruleId: AvoidPreserveWhitespaceFalseRule.new,
AvoidReturningWidgetsRule.ruleId: AvoidReturningWidgetsRule.new,
AvoidShrinkWrapInListsRule.ruleId: AvoidShrinkWrapInListsRule.new,
AvoidThrowInCatchBlockRule.ruleId: AvoidThrowInCatchBlockRule.new,
AvoidTopLevelMembersInTestsRule.ruleId: AvoidTopLevelMembersInTestsRule.new,
AvoidUnnecessarySetStateRule.ruleId: AvoidUnnecessarySetStateRule.new,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// ignore_for_file: public_member_api_docs

import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:collection/collection.dart';

import '../../../../../utils/flutter_types_utils.dart';
import '../../../../../utils/node_utils.dart';
import '../../../lint_utils.dart';
import '../../../models/internal_resolved_unit_result.dart';
import '../../../models/issue.dart';
import '../../../models/severity.dart';
import '../../models/flutter_rule.dart';
import '../../rule_utils.dart';

part 'visitor.dart';

class AvoidShrinkWrapInListsRule extends FlutterRule {
static const String ruleId = 'avoid-shrink-wrap-in-lists';

static const _warning =
'Avoid using ListView with shrinkWrap, since it might degrade the performance. Consider using slivers instead.';

AvoidShrinkWrapInListsRule([Map<String, Object> config = const {}])
: super(
id: ruleId,
severity: readSeverity(config, Severity.performance),
excludes: readExcludes(config),
);

@override
Iterable<Issue> check(InternalResolvedUnitResult source) {
final visitor = _Visitor();

source.unit.visitChildren(visitor);

return visitor.expressions
.map((expression) => createIssue(
rule: this,
location: nodeLocation(
node: expression,
source: source,
),
message: _warning,
))
.toList(growable: false);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
part of 'avoid_shrink_wrap_in_lists_rule.dart';

class _Visitor extends RecursiveAstVisitor<void> {
final _expressions = <Expression>[];

Iterable<Expression> get expressions => _expressions;

@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
super.visitInstanceCreationExpression(node);

if (isListViewWidget(node.staticType) &&
_hasShrinkWrap(node) &&
_hasParentList(node)) {
_expressions.add(node);
}
}

bool _hasShrinkWrap(InstanceCreationExpression node) =>
node.argumentList.arguments.firstWhereOrNull(
(arg) => arg is NamedExpression && arg.name.label.name == 'shrinkWrap',
) !=
null;

bool _hasParentList(InstanceCreationExpression node) =>
Copy link

@gabrielaraujoz gabrielaraujoz Jul 13, 2022

Choose a reason for hiding this comment

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

hey @incendial , awesome work! I took the liberty of reviewing your PR and I think there's one way to make it even better: when we have a list inside another like we're testing, we usually have to wrap them in an Expanded Widget (check the bad case scenario). Because of that, I believe it would be better if we test for that case as well in this rule.

WDYT? Does that make sense to you? Let me know if you need me to make the adjustments for you, I'd be glad to help!

Copy link
Member Author

@incendial incendial Jul 14, 2022

Choose a reason for hiding this comment

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

@gabrielaraujoz hi! Thanks for taking a look. Do you mean that we should first check if the ListView is in the Expanded and then if it's in the Column/Row/ListView?

Choose a reason for hiding this comment

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

Hey! If I'd do it, I'd check for both scenarios: if it's parent is an Expanded that has a Column/Row parent and the cases you're currently testing as well.

When working with Column and Row, if you have a widget with unbounded height/width you need to wrap it in a Flexible or Expanded, else you'll have the unbounded height/width exception. I don't believe this is necessary for ListViews tbh

Copy link
Member Author

Choose a reason for hiding this comment

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

@gabrielaraujoz but it looks like wrapping in Expanded is a subset of all cases when a ListView is in the Column/Row, isn't it? Meaning, that the current check already covers it

node.thisOrAncestorMatching((parent) =>
parent != node &&
parent is InstanceCreationExpression &&
(isListViewWidget(parent.staticType) ||
isColumnWidget(parent.staticType) ||
isRowWidget(parent.staticType))) !=
null;
}
15 changes: 12 additions & 3 deletions lib/src/utils/flutter_types_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,24 @@ bool isWidgetStateOrSubclass(DartType? type) =>
bool isSubclassOfListenable(DartType? type) =>
type is InterfaceType && type.allSupertypes.any(_isListenable);

bool isListViewWidget(DartType? type) =>
type?.getDisplayString(withNullability: false) == 'ListView';

bool isColumnWidget(DartType? type) =>
type?.getDisplayString(withNullability: false) == 'Column';

bool isRowWidget(DartType? type) =>
type?.getDisplayString(withNullability: false) == 'Row';

bool isPaddingWidget(DartType? type) =>
type?.getDisplayString(withNullability: false) == 'Padding';

bool _isWidget(DartType? type) =>
type?.getDisplayString(withNullability: false) == 'Widget';

bool isBuildContext(DartType? type) =>
type?.getDisplayString(withNullability: false) == 'BuildContext';

bool _isWidget(DartType? type) =>
type?.getDisplayString(withNullability: false) == 'Widget';

bool _isSubclassOfWidget(DartType? type) =>
type is InterfaceType && type.allSupertypes.any(_isWidget);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import 'package:dart_code_metrics/src/analyzers/lint_analyzer/models/severity.dart';
import 'package:dart_code_metrics/src/analyzers/lint_analyzer/rules/rules_list/avoid_shrink_wrap_in_lists/avoid_shrink_wrap_in_lists_rule.dart';
import 'package:test/test.dart';

import '../../../../../helpers/rule_test_helper.dart';

const _examplePath = 'avoid_shrink_wrap_in_lists/examples/example.dart';

void main() {
group('AvoidShrinkWrapInListsRule', () {
test('initialization', () async {
final unit = await RuleTestHelper.resolveFromFile(_examplePath);
final issues = AvoidShrinkWrapInListsRule().check(unit);

RuleTestHelper.verifyInitialization(
issues: issues,
ruleId: 'avoid-shrink-wrap-in-lists',
severity: Severity.performance,
);
});

test('reports about found issues', () async {
final unit = await RuleTestHelper.resolveFromFile(_examplePath);
final issues = AvoidShrinkWrapInListsRule().check(unit);

RuleTestHelper.verifyIssues(
issues: issues,
startLines: [10, 17, 24],
startColumns: [30, 27, 32],
locationTexts: [
'ListView(shrinkWrap: true, children: [])',
'ListView(shrinkWrap: true, children: [])',
'ListView(shrinkWrap: true, children: [])',
],
messages: [
'Avoid using ListView with shrinkWrap, since it might degrade the performance. Consider using slivers instead.',
'Avoid using ListView with shrinkWrap, since it might degrade the performance. Consider using slivers instead.',
'Avoid using ListView with shrinkWrap, since it might degrade the performance. Consider using slivers instead.',
],
);
});
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class CoolWidget {
Widget build() {
return ListView(child: Widget());
}
}

class WidgetWithColumn {
Widget build() {
// LINT
return Column(children: [ListView(shrinkWrap: true, children: [])]);
}
}

class WidgetWithRow {
Widget build() {
// LINT
return Row(children: [ListView(shrinkWrap: true, children: [])]);
}
}

class WidgetWithList {
Widget build() {
// LINT
return ListView(children: [ListView(shrinkWrap: true, children: [])]);
}
}

class ListView extends Widget {
final bool shrinkWrap;
final List<Widget> children;

const ListView({required this.shrinkWrap, required this.children});
}

class Column extends Widget {
final List<Widget> children;

const Column({required this.children});
}

class Row extends Widget {
final List<Widget> children;

const Row({required this.children});
}

class Widget {}
53 changes: 53 additions & 0 deletions website/docs/rules/flutter/avoid-shrink-wrap-in-lists.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Avoid shrink wrap in lists

## Rule id {#rule-id}

avoid-shrink-wrap-in-lists

## Severity {#severity}

Performance

## Description {#description}

Warns when a `ListView` widget with `shrinkWrap` parameter is wrapped in a `Column`, `Row` or another `ListView` widget.

According to the Flutter documentation, using `shrinkWrap` in lists is expensive performance-wise and should be avoided, since using slivers is significantly cheaper and achieves the same or even better results.

Additional resources:

- <https://github.com/dart-lang/linter/issues/3496>

### Example {#example}

Bad:

```dart
Column(
children: [
Expanded(
// LINT
child: ListView(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
children: [],
),
),
],
),
```

Good:

```dart
CustomScrollView(
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => Container(),
childCount: someObject.length,
),
),
],
),
```