-
Notifications
You must be signed in to change notification settings - Fork 170
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add unnecessary_stateful_widgets #3725
Open
a14n
wants to merge
9
commits into
dart-lang:main
Choose a base branch
from
a14n:unnecessary_stateful_widgets
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
accd246
unnecessary_stateful_widgets
a14n c659526
exception for state with field
a14n 4a4f128
exception for public state
a14n fc8fc04
exception for not direct extending StatefulWidget
a14n 59fca09
update all.yaml
a14n cd1a48b
remove leading whitespace
a14n ae79a1a
exception for Widget with Stateful in the name
a14n cad2266
exception for state usage
a14n dceae05
Add comment
a14n File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file | ||
// for details. All rights reserved. Use of this source code is governed by a | ||
// BSD-style license that can be found in the LICENSE file. | ||
|
||
import 'package:analyzer/dart/ast/ast.dart'; | ||
import 'package:analyzer/dart/ast/visitor.dart'; | ||
import 'package:analyzer/dart/element/element.dart'; | ||
import 'package:collection/collection.dart'; | ||
|
||
import '../analyzer.dart'; | ||
import '../extensions.dart'; | ||
import '../util/flutter_utils.dart'; | ||
|
||
const _desc = r'Unnecessary StatefulWidget.'; | ||
|
||
const _details = r''' | ||
Don't use `StatefulWidget` when a `StatelessWidget` is sufficient. Using a | ||
`StatelessWidget` where appropriate leads to more compact, concise, and readable | ||
code and is more idiomatic. | ||
|
||
**BAD:** | ||
|
||
```dart | ||
class MyWidget extends StatefulWidget { | ||
const MyWidget({super.key}); | ||
|
||
@override | ||
State<MyWidget> createState() => _MyWidgetState(); | ||
} | ||
|
||
class _MyWidgetState extends State<MyWidget> { | ||
@override | ||
Widget build(BuildContext context) { | ||
return Container(); | ||
} | ||
} | ||
``` | ||
|
||
**GOOD:** | ||
|
||
```dart | ||
class MyWidget extends StatelessWidget { | ||
const MyWidget({super.key}); | ||
|
||
@override | ||
Widget build(BuildContext context) { | ||
return Container(); | ||
} | ||
} | ||
``` | ||
|
||
'''; | ||
|
||
class UnnecessaryStatefulWidgets extends LintRule { | ||
UnnecessaryStatefulWidgets() | ||
: super( | ||
name: 'unnecessary_stateful_widgets', | ||
description: _desc, | ||
details: _details, | ||
group: Group.style, | ||
maturity: Maturity.experimental, | ||
); | ||
|
||
@override | ||
void registerNodeProcessors( | ||
NodeLintRegistry registry, | ||
LinterContext context, | ||
) { | ||
var visitor = _Visitor(this); | ||
registry.addCompilationUnit(this, visitor); | ||
} | ||
} | ||
|
||
class _Visitor extends SimpleAstVisitor<void> { | ||
_Visitor(this.rule); | ||
|
||
final LintRule rule; | ||
|
||
@override | ||
void visitCompilationUnit(CompilationUnit node) { | ||
var classes = node.declarations.whereType<ClassDeclaration>().toList(); | ||
widgetLoop: | ||
for (var statefulWidget in classes | ||
.where((e) => isExactStatefulWidget(e.declaredElement?.supertype))) { | ||
// if Stateful is used in name, we ignore it | ||
if (statefulWidget.name.lexeme.contains('Stateful')) continue; | ||
|
||
var createState = statefulWidget.members | ||
.whereType<MethodDeclaration>() | ||
.firstWhereOrNull((e) => e.name.lexeme == 'createState'); | ||
if (createState == null) continue; | ||
var createStateBody = createState.body; | ||
if (createStateBody is! ExpressionFunctionBody) continue; | ||
var stateElement = createStateBody.expression.staticType?.element2; | ||
if (stateElement is! ClassElement) continue; | ||
var stateName = stateElement.name; | ||
|
||
var stateDeclaration = | ||
classes.where((e) => e.name.lexeme == stateName).singleOrNull; | ||
if (stateDeclaration == null) continue; | ||
if (stateDeclaration.withClause != null) continue; | ||
// check state is private | ||
if (stateDeclaration.declaredElement?.isPublic ?? true) continue; | ||
// check `extends State` | ||
var extendsClause = stateDeclaration.extendsClause; | ||
if (extendsClause == null) continue; | ||
var parent = extendsClause.superclass.name.staticElement; | ||
if (parent is! ClassElement || !isExactState(parent)) continue; | ||
// check no field | ||
if (stateDeclaration.fields.isNotEmpty) continue; | ||
// check no overriden methods except `build` | ||
for (var method in stateDeclaration.methods) { | ||
if (method.name.lexeme == 'build') continue; | ||
if (method.declaredElement?.hasOverride ?? false) { | ||
continue widgetLoop; | ||
} | ||
} | ||
// check no `State` usage | ||
var visitor = _StateUsageVisitor(); | ||
stateDeclaration.accept(visitor); | ||
if (visitor.hasStateUsage) continue; | ||
|
||
rule.reportLintForToken(statefulWidget.name); | ||
} | ||
} | ||
} | ||
|
||
class _StateUsageVisitor extends RecursiveAstVisitor<void> { | ||
bool hasStateUsage = false; | ||
|
||
late ClassElement _stateElement; | ||
|
||
@override | ||
void visitClassDeclaration(ClassDeclaration node) { | ||
var stateElement = node.declaredElement; | ||
if (stateElement == null) return; | ||
_stateElement = stateElement; | ||
super.visitClassDeclaration(node); | ||
} | ||
|
||
@override | ||
void visitMethodInvocation(MethodInvocation node) { | ||
if (!_visit(node.canonicalElement)) { | ||
super.visitMethodInvocation(node); | ||
} | ||
} | ||
|
||
@override | ||
void visitSimpleIdentifier(SimpleIdentifier node) { | ||
if (node.name == 'widget' || !_visit(node.canonicalElement)) { | ||
super.visitSimpleIdentifier(node); | ||
} | ||
} | ||
|
||
bool _visit(Element? methodElement) { | ||
if (methodElement is ClassMemberElement && | ||
_stateElement.allSupertypes | ||
.whereNot((type) => type == _stateElement.thisType) | ||
.any((type) => type.element2 == methodElement.enclosingElement3)) { | ||
hasStateUsage = true; | ||
return true; | ||
} | ||
return false; | ||
} | ||
} | ||
|
||
extension on ClassDeclaration { | ||
Iterable<FieldDeclaration> get fields => | ||
members.whereType<FieldDeclaration>(); | ||
Iterable<MethodDeclaration> get methods => | ||
members.whereType<MethodDeclaration>(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you document what this method returns?