Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are keys used for in Flutter framework? [duplicate]

Tags:

flutter

Flutter is an amazing framework straightforward and easy to use. I must see that the documentation is very good but there are some concept that are still vague to me, for instance the key parameter. According to the documentation A Key is an identifier for Widgets, Elements and SemanticsNodes. It's clear, but why do I need to identify my widgets. So far I never used keys in my coding. Is there any benefits of using keys in my code? Thanks.

like image 350
Toni Joe Avatar asked May 03 '18 21:05

Toni Joe


People also ask

What is the purpose of Key in flutter?

Flutter commonly uses keys when it needs to uniquely identify specific widgets within a collection. Using keys also helps Flutter preserve the state of StatefulWidget s while they're being replaced with other widgets or just moved in the widget tree.

What are keys 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. Keys must be unique amongst the Elements with the same parent.

What is key and super in flutter?

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 .

What is key in flutter constructor?

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.


1 Answers

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. There are a few cases where you may need to use them though.

A common case is if you need to differentiate between widgets by their keys, ObjectKey and ValueKey can be useful for defining how the widgets are differentiated. An example is the PageStorageKey, and another is for lists with animated deletion: https://flutter.io/cookbook/gestures/dismissible/.

Another example is that if you have a child you want to access from a parent, you can make a GlobalKey in the parent and pass it to the child's constructor. Then you can do globalKey.state to get the child's state (say for example in a button press callback). Note that this shouldn't be used excessively as there are often better ways to get around it.

You probably won't ever have to think about it until you use a widget that tells you directly to define keys for its children.

like image 81
rmtmckenzie Avatar answered Sep 20 '22 23:09

rmtmckenzie