what does the super and key words do in a dart class? one example is the code below:
class CardTitle extends StatelessWidget {
final String title;
const CardTitle(this.title, **{Key key}**) : **super(key: key)**;
super(key: key) forwards to the constructor of the super class and passes the parameter key passed to MyHomepage to the super constructors key parameter (same as for MyHomepage({Key key}) ).
The key concept is flutters' way to keep a reference to state and access the state at different times or maintain it while modifying the widget tree. Flutter checks the previous state before re-rendering and if the previous widget is of the same type as the new one — it is going to maintain the old state.
A Key is an identifier for Widgets, Elements and SemanticsNodes. A new widget will only be used to update an existing element if its key is the same as the key of the current widget associated with the element. Google Developers.
The key identifies a widget, and this tells flutter whether a widget should be inflated new, or whether it should replace an existing widget in the tree during a build. Keys must be unique amongst the Elements with the same parent.
super
is used to call the constructor of the base class. So in your example, the constructor of CardTitle
is calling the constructor of StatelessWidget
.
Key
is a type used in Flutter to identify widgets and allows Flutter to know when a widget that's moved in the tree is the same as a widget that was previously in a different location. There's a good video about keys here: https://www.youtube.com/watch?v=kn0EOS-ZiIc
Keys are used as an identifier for Widgets, Elements and SemanticsNodes.You don't need to use Keys most of the time, the framework handles it for you and uses them internally to differentiate between widgets. For more on them see: https://flutter.dev/docs/development/ui/widgets-intro#keys
As for the Super keyword:
We see in your example the CardTitle widget extends the super class statelesswidget and in its constructor the ":" starts the "initializer list", a comma separated list of expressions executed before the constructors of the super classes and therefore also before the constructors body.
In the example in your question the key parameter passed to the constructor is forwarded to the named parameter key of the unnamed constructor of the super class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With