rspec/rules/S7122/dart/rule.adoc
github-actions[bot] d3a2169e4d
Create rule S7122: Unnecessary widget containers should be removed (avoid_unnecessary_containers) (#4392)
Co-authored-by: antonioaversa <antonioaversa@users.noreply.github.com>
2024-10-09 14:15:40 +00:00

65 lines
2.1 KiB
Plaintext

Widget containers wrapping a single widget with no other parameter modifying the behavior of the UI is unnecessary and should be removed.
== Why is this an issue?
https://api.flutter.dev/flutter/widgets/Container-class.html[`Container`] is a https://api.flutter.dev/flutter/widgets/StatelessWidget-class.html[`StatelessWidget`] that wraps a child widget and applies additional properties and transformations to it.
For example a container can:
* apply padding and margin
* add borders
* setting width and height
* apply geometrical transformations, such as rotation, translation, and scaling
When none of these features are used, the container solely wraps its child widget. In this case the container is unnecessary and can be removed, making the code shorter and the intent clearer.
== How to fix it
Remove the `Container` instance, replacing it with the `Widget` specified in its `child` parameter.
=== Code examples
==== Noncompliant code example
[source,dart,diff-id=1,diff-type=noncompliant]
----
Widget widgetBuilder() =>
Container(child: MyWidget());
----
==== Compliant solution
[source,dart,diff-id=1,diff-type=compliant]
----
Widget widgetBuilder() =>
MyWidget();
----
== Resources
=== Documentation
* Dart Docs - https://dart.dev/tools/linter-rules/avoid_unnecessary_containers[Dart Linter rule - avoid_unnecessary_containers]
* Flutter API Reference - https://api.flutter.dev/flutter/widgets/Container-class.html[Container class]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Unnecessary instance of 'Container'.
=== Highlighting
The identifier name of the constructor of `Container`: e.g. `Container` in `returningContainer() => Container(child: MyWidget())`.
The `new` keyword, if used, is not highlighted: e.g. `Container` in `returningContainer() => new Container(child: MyWidget())`.
If the "named constructor syntax" is used, the constructor name (`new`) and the period sign between the class name and the constructor name are also highlighted: e.g. `Container.new` in `returningContainer() => Container.new(child: MyWidget())`.
endif::env-github,rspecator-view[]