Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does super and Key do in flutter? [duplicate]

Tags:

flutter

dart

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)**;
like image 523
geekymano Avatar asked Mar 03 '19 12:03

geekymano


People also ask

What does Super key key do in Flutter?

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}) ).

What are keys in Flutter and when should you use them?

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.

What is key key in Dart?

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.

Why do we use key in constructor in Flutter?

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.


2 Answers

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

like image 141
Danny Tuppeny Avatar answered Oct 31 '22 18:10

Danny Tuppeny


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.

like image 36
Hussein Abdallah Avatar answered Oct 31 '22 16:10

Hussein Abdallah