Skip to content

lint: StatefulWidget could be a StatelessWidget #58868

@goderbauer

Description

@goderbauer

Occasionally, I see Flutter code where people use StatefulWidgets even though a StatelessWidget would have been sufficient. Example:

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();
  }
}

The State class doesn't store any state in member variables and it also doesn't use any of the properties provided by Sate (e.g. mounted). This could easily be refactored to be a more concise StatelessWidget:

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

I wonder if it would be possible to have a lint for this?

Of course, from a functional perspective using a StatefulWidget here is totally fine, the additional performance overhead of a StatefulWidget over a StatelessWidget is probably neglectable. However, using a StatelessWidget where appropriate leads to more compact, concise, and readable code and is more idiomatic, IMO.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-linterIssues with the analyzer's support for the linter packagelinter-lint-proposaltype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions