Skip to content
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
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 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 example/all.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ linter:
- unnecessary_overrides
- unnecessary_parenthesis
- unnecessary_raw_strings
- unnecessary_stateful_widgets
- unnecessary_statements
- unnecessary_string_escapes
- unnecessary_string_interpolations
Expand Down
2 changes: 2 additions & 0 deletions lib/src/rules.dart
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ import 'rules/unnecessary_nullable_for_final_variable_declarations.dart';
import 'rules/unnecessary_overrides.dart';
import 'rules/unnecessary_parenthesis.dart';
import 'rules/unnecessary_raw_strings.dart';
import 'rules/unnecessary_stateful_widgets.dart';
import 'rules/unnecessary_statements.dart';
import 'rules/unnecessary_string_escapes.dart';
import 'rules/unnecessary_string_interpolations.dart';
Expand Down Expand Up @@ -404,6 +405,7 @@ void registerLintRules({bool inTestMode = false}) {
..register(UnnecessaryOverrides())
..register(UnnecessaryParenthesis())
..register(UnnecessaryRawStrings())
..register(UnnecessaryStatefulWidgets())
..register(UnnecessaryStatements())
..register(UnnecessaryStringEscapes())
..register(UnnecessaryStringInterpolations())
Expand Down
172 changes: 172 additions & 0 deletions lib/src/rules/unnecessary_stateful_widgets.dart
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) {
Copy link
Member

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?

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>();
}
13 changes: 13 additions & 0 deletions lib/src/util/flutter_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ bool isBuildContext(DartType? type, {bool skipNullable = false}) =>

bool isExactWidget(ClassElement element) => _flutter.isExactWidget(element);

bool isExactState(ClassElement element) => _flutter.isExactState(element);

bool isExactWidgetTypeContainer(DartType? type) =>
_flutter.isExactWidgetTypeContainer(type);

Expand All @@ -40,6 +42,9 @@ bool isKDebugMode(Element? element) => _flutter.isKDebugMode(element);
bool isStatefulWidget(ClassElement? element) =>
_flutter.isStatefulWidget(element);

bool isExactStatefulWidget(DartType? type) =>
_flutter.isExactStatefulWidget(type);

bool isWidgetProperty(DartType? type) {
if (isWidgetType(type)) {
return true;
Expand All @@ -59,6 +64,7 @@ class _Flutter {
static const _nameBuildContext = 'BuildContext';
static const _nameStatefulWidget = 'StatefulWidget';
static const _nameWidget = 'Widget';
static const _nameState = 'State';
static const _nameContainer = 'Container';
static const _nameSizedBox = 'SizedBox';

Expand Down Expand Up @@ -102,6 +108,9 @@ class _Flutter {
bool isExactWidget(ClassElement element) =>
_isExactWidget(element, _nameWidget, _uriFramework);

bool isExactState(ClassElement element) =>
_isExactWidget(element, _nameState, _uriFramework);

bool isExactWidgetTypeContainer(DartType? type) =>
type is InterfaceType &&
_isExactWidget(type.element2, _nameContainer, _uriContainer);
Expand Down Expand Up @@ -130,6 +139,10 @@ class _Flutter {
return false;
}

bool isExactStatefulWidget(type) =>
type is InterfaceType &&
_isExactWidget(type.element2, _nameStatefulWidget, _uriFramework);

bool isWidget(InterfaceElement element) {
if (_isExactWidget(element, _nameWidget, _uriFramework)) {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,19 @@ abstract class State<T extends StatefulWidget> {
}

abstract class StatefulWidget extends Widget {
const StatefulWidget({Key key}) : super(key: key);
const StatefulWidget({Key? key}) : super(key: key);

State createState() => null;
}

abstract class StatelessWidget extends Widget {
const StatelessWidget({Key key}) : super(key: key);
const StatelessWidget({Key? key}) : super(key: key);

Widget build(BuildContext context) => null;
}

class Widget {
final Key key;
final Key? key;

const Widget({this.key});
}
Expand Down
Loading