The https://api.flutter.dev/flutter/widgets/Widget/Widget.html[`Widget` constructor] takes a `key` as a named parameter. However, such a parameter is optional:
This means that widgets inheriting from it can be created without a `key` parameter.
[source,dart]
----
class MyWidget extends Widget {
MyWidget() : super(); // No key parameter forwarded
}
----
The same applies to the https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html[`StatefulWidget`] and the https://api.flutter.dev/flutter/widgets/StatelessWidget-class.html[`StatelessWidget`].
They both define constructors with an optional `key` parameter, which:
* is forwarded to the `Widget` constructor when specified
* is not forwarded when omitted
That results in a widget with a `null` key.
While this is not a problem in itself, it is a good practice to always provide a `key` parameter to widgets, as it can be useful for debugging, testing, and performance optimizations.
For example, when a widget needs to potentially be rebuilt, Flutter compares the new widget with the old one to determine what has changed. If the widgets have the same key, Flutter assumes that they are the same, and it will not perform the rebuild. This can be useful when building the widget is expensive, or when the it has a state that should be preserved across rebuilds.
* Flutter API Reference - https://api.flutter.dev/flutter/widgets/Widget/Widget.html[Widget class - constructor]
* Flutter API Reference - https://api.flutter.dev/flutter/widgets/Widget/key.html[Widget class - key property]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Constructors for public widgets should have a named 'key' parameter.
=== Highlighting
If the widget class has no constructor declarations in it: the identifier name of the widget class: e.g. `MyWidget` in `class MyWidget { ... }`.
If the widget class has constructors declarations in it: the identifier name of the constructor missing the `key` parameter: e.g. `MyWidget` in `MyWidget()`. If the constructor is named, only the name of the constructor is highlighted, and the class name is not: e.g. `named` in `MyWidget.named()`.