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.
-
flutter.io/widgets-intro/#keysaqwert– aqwert2018-05-03 21:23:04 +00:00Commented May 3, 2018 at 21:23
-
1Thanks Rémi. That is exactly what I needed.Toni Joe– Toni Joe2018-05-03 21:51:17 +00:00Commented May 3, 2018 at 21:51
-
flutter.io/cookbook/forms/validation This will clear everything for you. @ToniJoesagar suri– sagar suri2018-06-15 05:43:24 +00:00Commented Jun 15, 2018 at 5:43
-
Keys could be used to enhance performance too...medium.com/flutter-community/…stuckedunderflow– stuckedunderflow2019-04-05 03:04:17 +00:00Commented Apr 5, 2019 at 3:04
1 Answer
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.
11 Comments
GlobalKey
is deprecated. You can almost always find a way to not use it. The most common usage of Key
is when you need to list animations on a children list. Such as add/remove, or a simple reorder.